{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "77bdd534-7dc1-4b2a-b7b5-8fdd21aad5dd",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'False,None,True,and,as,assert,async,await,break,class,continue,def,del,elif,else,except,finally,for,from,global,if,import,in,is,lambda,nonlocal,not,or,pass,raise,return,try,while,with,yield'"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import keyword\n",
    "\",\".join(keyword.kwlist)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "550f834e-82a6-4087-86f0-2d197ea0ce70",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "123456789\n",
      "12345678\n",
      "1\n",
      "345\n",
      "3456789\n",
      "24\n",
      "123456789123456789\n",
      "123456789你好\n",
      "------------------------------\n",
      "hello\n",
      "runoob\n",
      "hello\\nrunoob\n"
     ]
    }
   ],
   "source": [
    "str='123456789'\n",
    "print(str)                 # 输出字符串\n",
    "print(str[0:-1])           # 输出第一个到倒数第二个的所有字符\n",
    "print(str[0])              # 输出字符串第一个字符\n",
    "print(str[2:5])            # 输出从第三个开始到第六个的字符（不包含）\n",
    "print(str[2:])             # 输出从第三个开始后的所有字符\n",
    "print(str[1:5:2])          # 输出从第二个开始到第五个且每隔一个的字符（步长为2）\n",
    "print(str * 2)             # 输出字符串两次\n",
    "print(str + '你好')         # 连接字符串\n",
    "print('------------------------------')\n",
    "print('hello\\nrunoob')      # 使用反斜杠(\\)+n转义特殊字符\n",
    "print(r'hello\\nrunoob')     # 在字符串前面添加一个 r，表示原始字符串，不会发生转义"
   ]
  },
  {
   "cell_type": "raw",
   "id": "20515c28-baa1-4ebe-8cd2-d9b3ce3c04a7",
   "metadata": {},
   "source": [
    "Python3 中常见的数据类型有：\n",
    "\n",
    "Number（数字）\n",
    "String（字符串）\n",
    "bool（布尔类型）\n",
    "List（列表）\n",
    "Tuple（元组）\n",
    "Set（集合）\n",
    "Dictionary（字典）\n",
    "Python3 的六个标准数据类型中：\n",
    "\n",
    "不可变数据（3 个）：Number（数字）、String（字符串）、Tuple（元组）；\n",
    "可变数据（3 个）：List（列表）、Dictionary（字典）、Set（集合）。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2418265d-d21c-4330-9423-76bc8cc02482",
   "metadata": {},
   "source": [
    "# Python数据类型转换\n",
    "\n",
    "- int(x [,base])：将x转换为一个整数\n",
    "- float(x)：将x转换到一个浮点数\n",
    "- complex(real [,imag])：创建一个复数\n",
    "- str(x)：将对象 x 转换为字符串\n",
    "- repr(x)：将对象 x 转换为表达式字符串\n",
    "- eval(str)：用来计算在字符串中的有效Python表达式,并返回一个对象\n",
    "- tuple(s)：将序列 s 转换为一个元组\n",
    "- list(s)：将序列 s 转换为一个列表\n",
    "- set(s)：转换为可变集合\n",
    "- dict(d)：创建一个字典。d 必须是一个 (key, value)元组序列。\n",
    "- frozenset(s)：转换为不可变集合\n",
    "- chr(x)：将一个整数转换为一个字符\n",
    "- ord(x)：将一个字符转换为它的整数值\n",
    "- hex(x)：将一个整数转换为一个十六进制字符串\n",
    "- oct(x)：将一个整数转换为一个八进制字符串"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4914c871-2626-4385-a445-352b16ec83e3",
   "metadata": {},
   "source": [
    "# Python运算符优先级\n",
    "\n",
    "|运算符|描述|\n",
    "|--|--|\n",
    "|(expressions...),[expressions...], {key: value...}, {expressions...}|圆括号的表达式|\n",
    "|x[index], x[index:index], x(arguments...), x.attribute|读取，切片，调用，属性引用|\n",
    "|await x|await 表达式|\n",
    "|**|乘方(指数)|\n",
    "|+x, -x, ~x|正，负，按位非 NOT|\n",
    "|*, @, /, //, %|乘，矩阵乘，除，整除，取余|\n",
    "|+, -|加和减|\n",
    "|<<, >>|移位|\n",
    "|&|按位与 AND|\n",
    "|^|按位异或 XOR|\n",
    "|\\||按位或 OR|\n",
    "|in,not in, is,is not, <, <=, >, >=, !=, ==|比较运算，包括成员检测和标识号检测|\n",
    "|not x|逻辑非 NOT|\n",
    "|and|逻辑与 AND|\n",
    "|or|逻辑或 OR|\n",
    "|if -- else|条件表达式|\n",
    "|lambda|lambda 表达式|\n",
    "|:=|赋值表达式|"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8ea15ae0-2c44-46b7-a571-ee7b33e27543",
   "metadata": {},
   "source": [
    "# 数学函数\n",
    "\n",
    "|函数|返回值 ( 描述 )|\n",
    "|--|--|\n",
    "|abs(x)|返回数字的绝对值，如abs(-10) 返回 10|\n",
    "|ceil(x)|返回数字的上入整数，如math.ceil(4.1) 返回 5|\n",
    "|cmp(x, y)|如果 x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1。 Python 3 已废弃，使用 (x>y)-(x<y) 替换。|\n",
    "|exp(x)|返回e的x次幂(ex),如math.exp(1) 返回2.718281828459045|\n",
    "|fabs(x)|以浮点数形式返回数字的绝对值，如math.fabs(-10) 返回10.0|\n",
    "|floor(x)|返回数字的下舍整数，如math.floor(4.9)返回 4|\n",
    "|log(x)|如math.log(math.e)返回1.0,math.log(100,10)返回2.0|\n",
    "|log10(x)|返回以10为基数的x的对数，如math.log10(100)返回 2.0|\n",
    "|max(x1, x2,...)|返回给定参数的最大值，参数可以为序列。|\n",
    "|min(x1, x2,...)|返回给定参数的最小值，参数可以为序列。|\n",
    "|modf(x)|返回x的整数部分与小数部分，两部分的数值符号与x相同，整数部分以浮点型表示。|\n",
    "|pow(x, y)|x**y 运算后的值。|\n",
    "|round(x [,n])|返回浮点数 x 的四舍五入值，如给出 n 值，则代表舍入到小数点后的位数。其实准确的说是保留值将保留到离上一位更近的一端。|\n",
    "|sqrt(x)返回数字x的平方根。|"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9fb1115c-2db1-4960-b013-0345d836762f",
   "metadata": {},
   "source": [
    "# 随机数函数\n",
    "\n",
    "|函数|描述|\n",
    "|--|--|\n",
    "|choice(seq)|从序列的元素中随机挑选一个元素，比如random.choice(range(10))，从0到9中随机挑选一个整数。|\n",
    "|randrange ([start,] stop [,step])|从指定范围内，按指定基数递增的集合中获取一个随机数，基数默认值为 1|\n",
    "|random()|随机生成下一个实数，它在[0,1)范围内。|\n",
    "|seed([x])|改变随机数生成器的种子seed。如果你不了解其原理，你不必特别去设定seed，Python会帮你选择seed。|\n",
    "|shuffle(lst)|将序列的所有元素随机排序|\n",
    "|uniform(x, y)|随机生成下一个实数，它在[x,y]范围内。|"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b165befb-75bc-4a7c-aa45-b6a7ba531e09",
   "metadata": {},
   "source": [
    "# 三角函数\n",
    "\n",
    "|函数|描述|\n",
    "|--|--|\n",
    "|acos(x)|返回x的反余弦弧度值。|\n",
    "|asin(x)|返回x的反正弦弧度值。|\n",
    "|atan(x)|返回x的反正切弧度值。|\n",
    "|atan2(y, x)|返回给定的 X 及 Y 坐标值的反正切值。|\n",
    "|cos(x)|返回x的弧度的余弦值。|\n",
    "|hypot(x, y)|返回欧几里德范数 sqrt(x*x + y*y)。|\n",
    "|sin(x)|返回的x弧度的正弦值。|\n",
    "|tan(x)|返回x弧度的正切值。|\n",
    "|degrees(x)|将弧度转换为角度,如degrees(math.pi/2) ， 返回90.0|\n",
    "|radians(x)|将角度转换为弧度|"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7bc8d0c8-d5ff-4b20-ba0f-40e40d4543c5",
   "metadata": {},
   "source": [
    "# 数学常量\n",
    "\n",
    "|常量|描述|\n",
    "|--|--|\n",
    "|pi|数学常量 pi（圆周率，一般以π来表示）|\n",
    "|e|数学常量 e，e即自然常数（自然常数）。|"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8042e6c8-1ab5-40d9-93d7-0bd1539dd22d",
   "metadata": {},
   "source": [
    "# Python 转义字符\n",
    "\n",
    "|转义字符|描述|\n",
    "|--|--|\n",
    "|\\(在行尾时)|续行符|\n",
    "|\\\\|反斜杠符号|\n",
    "|\\'|单引号|\n",
    "|\\\"|双引号|\n",
    "|\\a|响铃|\n",
    "|\\b|退格(Backspace)|\n",
    "|\\000|空|\n",
    "|\\n|换行|\n",
    "|\\v|\\纵向制表符|\n",
    "|\\t|横向制表符|\n",
    "|\\r|回车，将 \\r 后面的内容移到字符串开头，并逐一替换开头部分的字符，直至将 \\r 后面的内容完全替换完成。|\n",
    "|\\f|换页|\n",
    "|\\yyy|八进制数，y 代表 0~7 的字符，例如：\\012 代表换行。|\n",
    "|\\xyy|十六进制数，以 \\x 开头，y 代表的字符，例如：\\x0a 代表换行|\n",
    "|\\other|其它的字符以普通格式输出|"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ebe9d1b4-463b-4994-9077-adbd384c2da8",
   "metadata": {},
   "source": [
    "# Python 字符串运算符\n",
    "\n",
    "|操作符|描述|\n",
    "|--|--|\n",
    "|+|字符串连接\ta + b|\n",
    "|*|重复输出字符串\ta*2|\n",
    "|[]|通过索引获取字符串中字符|\n",
    "|[ : ]|截取字符串中的一部分，遵循左闭右开原则，str[0:2] 是不包含第 3 个字符的。|\n",
    "|in|成员运算符 - 如果字符串中包含给定的字符返回 True|\n",
    "|not in|成员运算符 - 如果字符串中不包含给定的字符返回 True|\n",
    "|r/R|原始字符串 - 原始字符串：所有的字符串都是直接按照字面的意思来使用，没有转义特殊或不能打印的字符。 原始字符串除在字符串的第一个引号前加上字母 r（可以大小写）以外，与普通字符串有着几乎完全相同的语法。|\n",
    "|%|格式字符串\t请看下一节内容。|"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "62304c06-3925-42d8-8d37-ac2766424941",
   "metadata": {},
   "source": [
    "# Python 字符串格式化\n",
    "\n",
    "|符号|描述|\n",
    "|--|--|\n",
    "|%c|格式化字符及其ASCII码|\n",
    "|%s|格式化字符串|\n",
    "|%d|格式化整数|\n",
    "|%u|格式化无符号整型|\n",
    "|%o|格式化无符号八进制数|\n",
    "|%x|格式化无符号十六进制数|\n",
    "|%X|格式化无符号十六进制数（大写）|\n",
    "|%f|格式化浮点数字，可指定小数点后的精度|\n",
    "|%e|用科学计数法格式化浮点数|\n",
    "|%E|作用同%e，用科学计数法格式化浮点数|\n",
    "|%g|%f和%e的简写|\n",
    "|%G|%f 和 %E 的简写|\n",
    "|%p|用十六进制数格式化变量的地址|\n",
    "\n",
    "|符号|功能|\n",
    "|--|--|\n",
    "|*|定义宽度或者小数点精度|\n",
    "|-|用做左对齐|\n",
    "|+|在正数前面显示加号( + )|\n",
    "|<sp>|在正数前面显示空格|\n",
    "|#|在八进制数前面显示零('0')，在十六进制前面显示'0x'或者'0X'(取决于用的是'x'还是'X')|\n",
    "|0|显示的数字前面填充'0'而不是默认的空格|\n",
    "|%|'%%'输出一个单一的'%'|\n",
    "|(var)|映射变量(字典参数)|\n",
    "|m.n.|m 是显示的最小总宽度,n 是小数点后的位数(如果可用的话)|"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d3ddac8a-75a7-42d5-8310-3a6d35f3d882",
   "metadata": {},
   "source": [
    "# Python 的字符串内建函数\n",
    "\n",
    "|序号|方法及描述|\n",
    "|--|--|\n",
    "|capitalize()|将字符串的第一个字符转换为大写|\n",
    "|center(width, fillchar)|返回一个指定的宽度 width 居中的字符串，fillchar 为填充的字符，默认为空格。|\n",
    "|count(str, beg= 0,end=len(string))|返回 str 在 string 里面出现的次数，如果 beg 或者 end 指定则返回指定范围内 str 出现的次数|\n",
    "|bytes.decode(encoding=\"utf-8\", errors=\"strict\")|Python3 中没有 decode 方法，但我们可以使用 bytes 对象的 decode() 方法来解码给定的 bytes 对象，这个 bytes 对象可以由 str.encode() 来编码返回。|\n",
    "|encode(encoding='UTF-8',errors='strict')|以 encoding 指定的编码格式编码字符串，如果出错默认报一个ValueError 的异常，除非 errors 指定的是'ignore'或者'replace'|\n",
    "|endswith(suffix, beg=0, end=len(string))|检查字符串是否以 suffix 结束，如果 beg 或者 end 指定则检查指定的范围内是否以 suffix 结束，如果是，返回 True,否则返回 False。|\n",
    "|expandtabs(tabsize=8)|把字符串 string 中的 tab 符号转为空格，tab 符号默认的空格数是 8 。|\n",
    "|find(str, beg=0, end=len(string))|检测 str 是否包含在字符串中，如果指定范围 beg 和 end ，则检查是否包含在指定范围内，如果包含返回开始的索引值，否则返回-1|\n",
    "|index(str, beg=0, end=len(string))|跟find()方法一样，只不过如果str不在字符串中会报一个异常。|\n",
    "|isalnum()|检查字符串是否由字母和数字组成，即字符串中的所有字符都是字母或数字。如果字符串至少有一个字符，并且所有字符都是字母或数字，则返回 True；否则返回 False。|\n",
    "|isalpha()|如果字符串至少有一个字符并且所有字符都是字母或中文字则返回 True, 否则返回 False|\n",
    "|isdigit()|如果字符串只包含数字则返回 True 否则返回 False..|\n",
    "|islower()|如果字符串中包含至少一个区分大小写的字符，并且所有这些(区分大小写的)字符都是小写，则返回 True，否则返回 False|\n",
    "|isnumeric()|如果字符串中只包含数字字符，则返回 True，否则返回 False|\n",
    "|isspace()|如果字符串中只包含空白，则返回 True，否则返回 False.|\n",
    "|istitle()|如果字符串是标题化的(见 title())则返回 True，否则返回 False|\n",
    "|isupper()|如果字符串中包含至少一个区分大小写的字符，并且所有这些(区分大小写的)字符都是大写，则返回 True，否则返回 False|\n",
    "|join(seq)|以指定字符串作为分隔符，将 seq 中所有的元素(的字符串表示)合并为一个新的字符串|\n",
    "|len(string)|返回字符串长度|\n",
    "|ljust(width[, fillchar])|返回一个原字符串左对齐,并使用 fillchar 填充至长度 width 的新字符串，fillchar 默认为空格。|\n",
    "|lower()|转换字符串中所有大写字符为小写.|\n",
    "|lstrip()|截掉字符串左边的空格或指定字符。|\n",
    "|maketrans()|创建字符映射的转换表，对于接受两个参数的最简单的调用方式，第一个参数是字符串，表示需要转换的字符，第二个参数也是字符串表示转换的目标。|\n",
    "|max(str)|返回字符串 str 中最大的字母。|\n",
    "|min(str)|返回字符串 str 中最小的字母。|\n",
    "|replace(old, new [, max])|把 将字符串中的 old 替换成 new,如果 max 指定，则替换不超过 max 次。|\n",
    "|rfind(str, beg=0,end=len(string))|类似于 find()函数，不过是从右边开始查找.|\n",
    "|rindex( str, beg=0, end=len(string))|类似于 index()，不过是从右边开始.|\n",
    "|rjust(width,[, fillchar])|返回一个原字符串右对齐,并使用fillchar(默认空格）填充至长度 width 的新字符串|\n",
    "|rstrip()|删除字符串末尾的空格或指定字符。|\n",
    "|split(str=\"\", num=string.count(str))|以 str 为分隔符截取字符串，如果 num 有指定值，则仅截取 num+1 个子字符串|\n",
    "|splitlines([keepends])|按照行('\\r', '\\r\\n', \\n')分隔，返回一个包含各行作为元素的列表，如果参数 keepends 为 False，不包含换行符，如果为 True，则保留换行符。|\n",
    "|startswith(substr, beg=0,end=len(string))|检查字符串是否是以指定子字符串 substr 开头，是则返回 True，否则返回 False。如果beg 和 end 指定值，则在指定范围内检查。|\n",
    "|strip([chars])|在字符串上执行 lstrip()和 rstrip()|\n",
    "|swapcase()|将字符串中大写转换为小写，小写转换为大写|\n",
    "|title()|返回\"标题化\"的字符串,就是说所有单词都是以大写开始，其余字母均为小写(见 istitle())|\n",
    "|translate(table, deletechars=\"\")|根据 table 给出的表(包含 256 个字符)转换 string 的字符, 要过滤掉的字符放到 deletechars 参数中|\n",
    "|upper()|转换字符串中的小写字母为大写|\n",
    "|zfill (width)|返回长度为 width 的字符串，原字符串右对齐，前面填充0|\n",
    "|isdecimal()|检查字符串是否只包含十进制字符，如果是返回 true，否则返回 false。|"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "938e9d89-e578-48cd-91a1-037735970cb3",
   "metadata": {},
   "source": [
    "# Python列表函数&方法\n",
    "\n",
    "|函数方法|备注|\n",
    "|--|--|\n",
    "|len(list)|列表元素个数|\n",
    "|max(list)|返回列表元素最大值|\n",
    "|min(list)|返回列表元素最小值|\n",
    "|list(seq)|将元组转换为列表|\n",
    "|list.append(obj)|在列表末尾添加新的对象|\n",
    "|list.count(obj)|统计某个元素在列表中出现的次数|\n",
    "|list.extend(seq)|在列表末尾一次性追加另一个序列中的多个值（用新列表扩展原来的列表）|\n",
    "|list.index(obj)|从列表中找出某个值第一个匹配项的索引位置|\n",
    "|list.insert(index, obj)|将对象插入列表|\n",
    "|list.pop([index=-1])|移除列表中的一个元素（默认最后一个元素），并且返回该元素的值|\n",
    "|list.remove(obj)|移除列表中某个值的第一个匹配项|\n",
    "|list.reverse()|反向列表中元素|\n",
    "|list.sort( key=None, reverse=False)|对原列表进行排序|\n",
    "|list.clear()|清空列表|\n",
    "|list.copy()|复制列表|"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bf9e6675-b09e-41ec-87b2-2dddaac9658e",
   "metadata": {},
   "source": [
    "# 元组内置函数\n",
    "\n",
    "|方法|描述|\n",
    "|--|--|\n",
    "|len(tuple)|计算元组元素个数。\t|\n",
    "|max(tuple)|返回元组中元素最大值。|\t\n",
    "|min(tuple)|返回元组中元素最小值。\t|\n",
    "|tuple(iterable)|将可迭代系列转换为元组。|"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "06cc736f-397e-44b5-b2f1-e8e854c8632c",
   "metadata": {},
   "source": [
    "# 字典内置函数&方法\n",
    "\n",
    "|函数|描述|\n",
    "|--|--|\n",
    "|len(dict)|计算字典元素个数，即键的总数。|\n",
    "|str(dict)|输出字典，可以打印的字符串表示。|\n",
    "|type(variable)|返回输入的变量类型，如果变量是字典就返回字典类型。|\n",
    "\n",
    "|方法|描述|\n",
    "|--|--|\n",
    "|dict.clear()|删除字典内所有元素|\n",
    "|dict.copy()|返回一个字典的浅复制|\n",
    "|dict.fromkeys()|创建一个新字典，以序列seq中元素做字典的键，val为字典所有键对应的初始值|\n",
    "|dict.get(key, default=None)|返回指定键的值，如果键不在字典中返回 default 设置的默认值|\n",
    "|key in dict|如果键在字典dict里返回true，否则返回false|\n",
    "|dict.items()|以列表返回一个视图对象|\n",
    "|dict.keys()|返回一个视图对象|\n",
    "|dict.setdefault(key, default=None)|和get()类似, 但如果键不存在于字典中，将会添加键并将值设为default|\n",
    "|dict.update(dict2)|把字典dict2的键/值对更新到dict里|\n",
    "|dict.values()|返回一个视图对象|\n",
    "|dict.pop(key[,default])|删除字典 key（键）所对应的值，返回被删除的值。|\n",
    "|dict.popitem()|返回并删除字典中的最后一对键和值。|"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "01603993-c249-4a04-acae-f537d6b98d4e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'Age': 7, 'Class': 'First'}\n"
     ]
    }
   ],
   "source": [
    "tinydict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}\n",
    "del tinydict['Name'] # 删除键 'Name'\n",
    "print(tinydict)\n",
    "tinydict.clear()     # 清空字典\n",
    "del tinydict         # 删除字典"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e89280d0-13a7-4069-89a4-05bfdea22120",
   "metadata": {},
   "source": [
    "# 集合内置方法完整列表\n",
    "\n",
    "|方法|描述|\n",
    "|--|--|\n",
    "|add()|为集合添加元素|\n",
    "|clear()|移除集合中的所有元素|\n",
    "|copy()|拷贝一个集合|\n",
    "|difference()|返回多个集合的差集|\n",
    "|difference_update()|移除集合中的元素，该元素在指定的集合也存在。|\n",
    "|discard()|删除集合中指定的元素|\n",
    "|intersection()|返回集合的交集|\n",
    "|intersection_update()|返回集合的交集。|\n",
    "|isdisjoint()|判断两个集合是否包含相同的元素，如果没有返回 True，否则返回 False。|\n",
    "|issubset()|判断指定集合是否为该方法参数集合的子集。|\n",
    "|issuperset()|判断该方法的参数集合是否为指定集合的子集|\n",
    "|pop()|随机移除元素|\n",
    "|remove()|移除指定元素|\n",
    "|symmetric_difference()|返回两个集合中不重复的元素集合。|\n",
    "|symmetric_difference_update()|移除当前集合中在另外一个指定集合相同的元素，并将另外一个指定集合中不同的元素插入到当前集合中。|\n",
    "|union()|返回两个集合的并集|\n",
    "|update()|给集合添加元素|\n",
    "|len()|计算集合元素个数|"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "679ff6c4-767e-4cd4-bb2f-5e654fd2cdbb",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Bad request\n"
     ]
    }
   ],
   "source": [
    "def http_error(status):\n",
    "    match status:\n",
    "        case 400:\n",
    "            return \"Bad request\"\n",
    "        case 404:\n",
    "            return \"Not found\"\n",
    "        case 418:\n",
    "            return \"I'm a teapot\"\n",
    "        case _:\n",
    "            return \"Something's wrong with the internet\"\n",
    "\n",
    "mystatus=400\n",
    "print(http_error(400))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "f2ea18eb-8e4b-4d7a-9b42-46a6279836aa",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0  小于 5\n",
      "1  小于 5\n",
      "2  小于 5\n",
      "3  小于 5\n",
      "4  小于 5\n",
      "5  大于或等于 5\n"
     ]
    }
   ],
   "source": [
    "count = 0\n",
    "while count < 5:\n",
    "   print (count, \" 小于 5\")\n",
    "   count = count + 1\n",
    "else:\n",
    "   print (count, \" 大于或等于 5\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "c220c2ad-8548-4404-b102-c45a7a9738a1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "循环数据 Baidu\n",
      "循环数据 Google\n",
      "菜鸟教程!\n",
      "完成循环!\n"
     ]
    }
   ],
   "source": [
    "sites = [\"Baidu\", \"Google\",\"Runoob\",\"Taobao\"]\n",
    "for site in sites:\n",
    "    if site == \"Runoob\":\n",
    "        print(\"菜鸟教程!\")\n",
    "        break\n",
    "    print(\"循环数据 \" + site)\n",
    "else:\n",
    "    print(\"没有循环数据!\")\n",
    "print(\"完成循环!\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "13dfd81e-3fab-4b3f-a08e-81ea9aad1b8f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2  是质数\n",
      "3  是质数\n",
      "4 等于 2 * 2\n",
      "5  是质数\n",
      "6 等于 2 * 3\n",
      "7  是质数\n",
      "8 等于 2 * 4\n",
      "9 等于 3 * 3\n"
     ]
    }
   ],
   "source": [
    "for n in range(2, 10):\n",
    "    for x in range(2, n):\n",
    "        if n % x == 0:\n",
    "            print(n, '等于', x, '*', n//x)\n",
    "            break\n",
    "    else:\n",
    "        # 循环中没有找到元素\n",
    "        print(n, ' 是质数')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "87ed6784-3e84-4d39-a905-90c8c7536fe3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "当前变量值 : 9\n",
      "当前变量值 : 8\n",
      "当前变量值 : 7\n",
      "当前变量值 : 6\n",
      "当前变量值 : 4\n",
      "当前变量值 : 3\n",
      "当前变量值 : 2\n",
      "当前变量值 : 1\n",
      "当前变量值 : 0\n",
      "Good bye!\n"
     ]
    }
   ],
   "source": [
    "var = 10                    # 第二个实例\n",
    "while var > 0:              \n",
    "   var = var -1\n",
    "   if var == 5:             # 变量为 5 时跳过输出\n",
    "      continue\n",
    "   print ('当前变量值 :', var)\n",
    "print (\"Good bye!\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "f8e1ad2d-856a-4eea-bfae-53d214f22d5f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['ALICE', 'JERRY', 'WENDY', 'SMITH']\n"
     ]
    }
   ],
   "source": [
    "names = ['Bob','Tom','alice','Jerry','Wendy','Smith']\n",
    "new_names = [name.upper()for name in names if len(name)>3]\n",
    "print(new_names)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "2ba5e8fb-8054-42ff-b0f8-551d91db62a1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "2\n",
      "3\n",
      "4\n",
      "5\n"
     ]
    }
   ],
   "source": [
    "# 创建一个迭代器\n",
    "\n",
    "class MyNumbers:\n",
    "  def __iter__(self):\n",
    "    self.a = 1\n",
    "    return self\n",
    " \n",
    "  def __next__(self):\n",
    "    x = self.a\n",
    "    self.a += 1\n",
    "    return x\n",
    " \n",
    "myclass = MyNumbers()\n",
    "myiter = iter(myclass)\n",
    " \n",
    "print(next(myiter))\n",
    "print(next(myiter))\n",
    "print(next(myiter))\n",
    "print(next(myiter))\n",
    "print(next(myiter))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "596422d7-989d-4e4b-8d3c-5a46c66686a7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5\n",
      "4\n",
      "3\n",
      "2\n",
      "1\n"
     ]
    }
   ],
   "source": [
    "# 生成器函数\n",
    "\n",
    "def countdown(n):\n",
    "    while n > 0:\n",
    "        yield n\n",
    "        n -= 1\n",
    " \n",
    "# 创建生成器对象\n",
    "generator = countdown(5)\n",
    " \n",
    "# 通过迭代生成器获取值\n",
    "print(next(generator))  # 输出: 5\n",
    "print(next(generator))  # 输出: 4\n",
    "print(next(generator))  # 输出: 3\n",
    " \n",
    "# 使用 for 循环迭代生成器\n",
    "for value in generator:\n",
    "    print(value)  # 输出: 2 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "194ddc16-4df7-44fa-bbcb-6926f54cf4a5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0 1 1 2 3 5 8 13 21 34 55 "
     ]
    }
   ],
   "source": [
    "# 使用 yield 实现斐波那契数列\n",
    "\n",
    "def fibonacci(n): # 生成器函数 - 斐波那契\n",
    "    a, b, counter = 0, 1, 0\n",
    "    while True:\n",
    "        if (counter > n): \n",
    "            return\n",
    "        yield a\n",
    "        a, b = b, a + b\n",
    "        counter += 1\n",
    "\n",
    "n = 11\n",
    "f = fibonacci(n) # f 是一个迭代器，由生成器返回生成\n",
    "\n",
    "while n > 0:\n",
    "    print (next(f), end=\" \")\n",
    "    n -= 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "1ec9e6dd-b4d0-4268-92cb-bfee6e7f71f5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "输出: \n",
      "10\n",
      "输出: \n",
      "70\n",
      "60\n",
      "50\n"
     ]
    }
   ],
   "source": [
    "# 不定长参数\n",
    "\n",
    "def printinfo( arg1, *vartuple ):\n",
    "   \"打印任何传入的参数\"\n",
    "   print (\"输出: \")\n",
    "   print (arg1)\n",
    "   for var in vartuple:\n",
    "      print (var)\n",
    "   return\n",
    " \n",
    "# 调用printinfo 函数\n",
    "printinfo( 10 )\n",
    "printinfo( 70, 60, 50 )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "b2c7c34c-b84a-4e90-b9f5-fa8a01d4142a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "输出: \n",
      "1\n",
      "{'a': 2, 'b': 3}\n"
     ]
    }
   ],
   "source": [
    "def printinfo( arg1, **vardict ):\n",
    "   \"打印任何传入的参数\"\n",
    "   print (\"输出: \")\n",
    "   print (arg1)\n",
    "   print (vardict)\n",
    " \n",
    "# 调用printinfo 函数\n",
    "printinfo(1, a=2,b=3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "dc444b7a-14bb-4868-9629-a5570cb74155",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "相加后的值为 :  30\n",
      "相加后的值为 :  40\n"
     ]
    }
   ],
   "source": [
    "# 匿名函数\n",
    "\n",
    "sum = lambda arg1, arg2: arg1 + arg2\n",
    " \n",
    "# 调用sum函数\n",
    "print (\"相加后的值为 : \", sum( 10, 20 ))\n",
    "print (\"相加后的值为 : \", sum( 20, 20 ))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "35776fa7-8076-4097-a4ee-04b50bb8a03a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10 20 30 40 50 60\n"
     ]
    }
   ],
   "source": [
    "# 强制位置参数\n",
    "\n",
    "def f(a, b, /, c, d, *, e, f):\n",
    "    print(a, b, c, d, e, f)\n",
    "\n",
    "f(10, 20, 30, d=40, e=50, f=60)\n",
    "\n",
    "# f(10, b=20, c=30, d=40, e=50, f=60)   # b 不能使用关键字参数的形式\n",
    "# f(10, 20, 30, 40, 50, f=60)           # e 必须使用关键字参数的形式"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "055cf19c-03b9-4baa-8b0c-daff9b99c13d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 4, 9, 16, 25]\n"
     ]
    }
   ],
   "source": [
    "numbers = [1, 2, 3, 4, 5]\n",
    "squared = list(map(lambda x: x**2, numbers))\n",
    "print(squared)  # 输出: [1, 4, 9, 16, 25]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "c879f65c-e2b3-4d61-8ee9-d4caa8f6c0d6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[2, 4, 6, 8]\n"
     ]
    }
   ],
   "source": [
    "numbers = [1, 2, 3, 4, 5, 6, 7, 8]\n",
    "even_numbers = list(filter(lambda x: x % 2 == 0, numbers))\n",
    "print(even_numbers)  # 输出：[2, 4, 6, 8]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "1609d844-3c1c-4002-94f2-bbd418c330e9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "120\n"
     ]
    }
   ],
   "source": [
    "from functools import reduce\n",
    "numbers = [1, 2, 3, 4, 5]\n",
    "# 使用 reduce() 和 lambda 函数计算乘积\n",
    "product = reduce(lambda x, y: x * y, numbers)\n",
    "print(product)  # 输出：120"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "70b934f2-8009-428a-8fab-790d958e05b5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "在原函数之前执行\n",
      "Hello!\n",
      "在原函数之后执行\n"
     ]
    }
   ],
   "source": [
    "def my_decorator(func):\n",
    "    def wrapper():\n",
    "        print(\"在原函数之前执行\")\n",
    "        func()\n",
    "        print(\"在原函数之后执行\")\n",
    "    return wrapper\n",
    "\n",
    "@my_decorator\n",
    "def say_hello():\n",
    "    print(\"Hello!\")\n",
    "\n",
    "say_hello()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "8b7e5007-93b1-4cfc-8c92-ee6c4ae067e2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "在原函数之前执行\n",
      "Hello, Alice!\n",
      "在原函数之后执行\n"
     ]
    }
   ],
   "source": [
    "def my_decorator(func):\n",
    "    def wrapper(*args, **kwargs):\n",
    "        print(\"在原函数之前执行\")\n",
    "        func(*args, **kwargs)\n",
    "        print(\"在原函数之后执行\")\n",
    "    return wrapper\n",
    "\n",
    "@my_decorator\n",
    "def greet(name):\n",
    "    print(f\"Hello, {name}!\")\n",
    "\n",
    "greet(\"Alice\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "088772af-0d67-4063-a44f-75a930303cd7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello!\n",
      "Hello!\n",
      "Hello!\n"
     ]
    }
   ],
   "source": [
    "def repeat(num_times):\n",
    "    def decorator(func):\n",
    "        def wrapper(*args, **kwargs):\n",
    "            for _ in range(num_times):\n",
    "                func(*args, **kwargs)\n",
    "        return wrapper\n",
    "    return decorator\n",
    "\n",
    "@repeat(3)\n",
    "def say_hello():\n",
    "    print(\"Hello!\")\n",
    "\n",
    "say_hello()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "c7584aeb-f050-4212-8d20-1598300bc145",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "abc\n",
      "在类方法之前执行\n",
      "这是 MyClass 的 display 方法\n",
      "在类方法之后执行\n"
     ]
    }
   ],
   "source": [
    "def my_decorator(cls):\n",
    "    class Wrapper:\n",
    "        def __init__(self, *args, **kwargs):\n",
    "            self.wrapped = cls(*args, **kwargs)\n",
    "\n",
    "        def display(self):\n",
    "            print(\"在类方法之前执行\")\n",
    "            self.wrapped.display()\n",
    "            print(\"在类方法之后执行\")\n",
    "    return Wrapper\n",
    "\n",
    "@my_decorator\n",
    "class MyClass:\n",
    "    def display(self):\n",
    "        print(\"这是 MyClass 的 display 方法\")\n",
    "\n",
    "obj = MyClass()\n",
    "print(\"abc\")\n",
    "obj.display()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e2267205-1220-4160-b588-7812f56648f0",
   "metadata": {},
   "source": [
    "# 内置装饰器\n",
    "\n",
    "@staticmethod: 将方法定义为静态方法，不需要实例化类即可调用。\n",
    "\n",
    "@classmethod: 将方法定义为类方法，第一个参数是类本身（通常命名为 cls）。\n",
    "\n",
    "@property: 将方法转换为属性，使其可以像属性一样访问。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "8374ee2e-50d6-45d7-af73-0acfddd71076",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "This is a static method.\n",
      "This is a class method of MyClass.\n",
      "a\n",
      "b\n",
      "c\n",
      "Alice\n"
     ]
    }
   ],
   "source": [
    "class MyClass:\n",
    "    @staticmethod\n",
    "    def static_method():\n",
    "        print(\"This is a static method.\")\n",
    "\n",
    "    @classmethod\n",
    "    def class_method(cls):\n",
    "        print(f\"This is a class method of {cls.__name__}.\")\n",
    "\n",
    "    @property\n",
    "    def name(self):\n",
    "        return self._name\n",
    "\n",
    "    @name.setter\n",
    "    def name(self, value):\n",
    "        self._name = value\n",
    "\n",
    "# 使用\n",
    "MyClass.static_method()\n",
    "MyClass.class_method()\n",
    "print(\"a\")\n",
    "obj = MyClass()\n",
    "print(\"b\")\n",
    "obj.name = \"Alice\"\n",
    "print(\"c\")\n",
    "print(obj.name)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "41dda23c-a301-4448-b19f-3f95fb35ce1f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a\n",
      "Decorator 1\n",
      "Decorator 2\n",
      "Hello!\n",
      "b\n"
     ]
    }
   ],
   "source": [
    "def decorator1(func):\n",
    "    def wrapper():\n",
    "        print(\"Decorator 1\")\n",
    "        func()\n",
    "    return wrapper\n",
    "\n",
    "def decorator2(func):\n",
    "    def wrapper():\n",
    "        print(\"Decorator 2\")\n",
    "        func()\n",
    "    return wrapper\n",
    "\n",
    "@decorator1\n",
    "@decorator2\n",
    "def say_hello():\n",
    "    print(\"Hello!\")\n",
    "\n",
    "print(\"a\")\n",
    "say_hello()\n",
    "print(\"b\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5bafdec7-ae11-40f2-8379-cdf051f896cc",
   "metadata": {},
   "source": [
    "# 列表\n",
    "\n",
    "|方法|描述|\n",
    "|--|--|\n",
    "|list.append(x)|把一个元素添加到列表的结尾，相当于 a[len(a):] = [x]。|\n",
    "|list.extend(L)|通过添加指定列表的所有元素来扩充列表，相当于 a[len(a):] = L。|\n",
    "|list.insert(i, x)|在指定位置插入一个元素。第一个参数是准备插入到其前面的那个元素的索引，例如 a.insert(0, x) 会插入到整个列表之前，而 a.insert(len(a), x) 相当于 a.append(x) 。|\n",
    "|list.remove(x)|删除列表中值为 x 的第一个元素。如果没有这样的元素，就会返回一个错误。|\n",
    "|list.pop([i])|从列表的指定位置移除元素，并将其返回。如果没有指定索引，a.pop()返回最后一个元素。元素随即从列表中被移除。（方法中 i 两边的方括号表示这个参数是可选的，而不是要求你输入一对方括号，你会经常在 Python 库参考手册中遇到这样的标记。）|\n",
    "|list.clear()|移除列表中的所有项，等于del a[:]。|\n",
    "|list.index(x)|返回列表中第一个值为 x 的元素的索引。如果没有匹配的元素就会返回一个错误。|\n",
    "|list.count(x)|返回 x 在列表中出现的次数。|\n",
    "|list.sort()|对列表中的元素进行排序。|\n",
    "|list.reverse()|倒排列表中的元素。|\n",
    "|list.copy()|返回列表的浅复制，等于a[:]。|"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "b88d14a8-1983-4826-acec-ab9cffcb04c6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "栈顶元素: 3\n",
      "栈大小: 3\n",
      "弹出元素: 3\n",
      "栈是否为空: False\n",
      "栈大小: 2\n"
     ]
    }
   ],
   "source": [
    "class Stack:\n",
    "    def __init__(self):\n",
    "        self.stack = []\n",
    "\n",
    "    def push(self, item):\n",
    "        self.stack.append(item)\n",
    "\n",
    "    def pop(self):\n",
    "        if not self.is_empty():\n",
    "            return self.stack.pop()\n",
    "        else:\n",
    "            raise IndexError(\"pop from empty stack\")\n",
    "\n",
    "    def peek(self):\n",
    "        if not self.is_empty():\n",
    "            return self.stack[-1]\n",
    "        else:\n",
    "            raise IndexError(\"peek from empty stack\")\n",
    "\n",
    "    def is_empty(self):\n",
    "        return len(self.stack) == 0\n",
    "\n",
    "    def size(self):\n",
    "        return len(self.stack)\n",
    "\n",
    "# 使用示例\n",
    "stack = Stack()\n",
    "stack.push(1)\n",
    "stack.push(2)\n",
    "stack.push(3)\n",
    "\n",
    "print(\"栈顶元素:\", stack.peek())  # 输出: 栈顶元素: 3\n",
    "print(\"栈大小:\", stack.size())    # 输出: 栈大小: 3\n",
    "\n",
    "print(\"弹出元素:\", stack.pop())  # 输出: 弹出元素: 3\n",
    "print(\"栈是否为空:\", stack.is_empty())  # 输出: 栈是否为空: False\n",
    "print(\"栈大小:\", stack.size())    # 输出: 栈大小: 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "fc455545-15a4-4383-a2ea-77fdcb0e238e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "队列状态: deque(['a', 'b', 'c'])\n",
      "移除的元素: a\n",
      "队列状态: deque(['b', 'c'])\n",
      "队首元素: b\n",
      "队列是否为空: False\n",
      "队列大小: 2\n"
     ]
    }
   ],
   "source": [
    "# 将列表当作队列使用\n",
    "\n",
    "from collections import deque\n",
    "\n",
    "# 创建一个空队列\n",
    "queue = deque()\n",
    "\n",
    "# 向队尾添加元素\n",
    "queue.append('a')\n",
    "queue.append('b')\n",
    "queue.append('c')\n",
    "\n",
    "print(\"队列状态:\", queue)  # 输出: 队列状态: deque(['a', 'b', 'c'])\n",
    "\n",
    "# 从队首移除元素\n",
    "first_element = queue.popleft()\n",
    "print(\"移除的元素:\", first_element)  # 输出: 移除的元素: a\n",
    "print(\"队列状态:\", queue)            # 输出: 队列状态: deque(['b', 'c'])\n",
    "\n",
    "# 查看队首元素（不移除）\n",
    "front_element = queue[0]\n",
    "print(\"队首元素:\", front_element)    # 输出: 队首元素: b\n",
    "\n",
    "# 检查队列是否为空\n",
    "is_empty = len(queue) == 0\n",
    "print(\"队列是否为空:\", is_empty)     # 输出: 队列是否为空: False\n",
    "\n",
    "# 获取队列大小\n",
    "size = len(queue)\n",
    "print(\"队列大小:\", size)            # 输出: 队列大小: 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "498a8748-2e85-44e2-9052-08ee5347fd91",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "队首元素: a\n",
      "队列大小: 3\n",
      "移除的元素: a\n",
      "队列是否为空: False\n",
      "队列大小: 2\n"
     ]
    }
   ],
   "source": [
    "# 使用列表实现队列\n",
    "\n",
    "class Queue:\n",
    "    def __init__(self):\n",
    "        self.queue = []\n",
    "\n",
    "    def enqueue(self, item):\n",
    "        self.queue.append(item)\n",
    "\n",
    "    def dequeue(self):\n",
    "        if not self.is_empty():\n",
    "            return self.queue.pop(0)\n",
    "        else:\n",
    "            raise IndexError(\"dequeue from empty queue\")\n",
    "\n",
    "    def peek(self):\n",
    "        if not self.is_empty():\n",
    "            return self.queue[0]\n",
    "        else:\n",
    "            raise IndexError(\"peek from empty queue\")\n",
    "\n",
    "    def is_empty(self):\n",
    "        return len(self.queue) == 0\n",
    "\n",
    "    def size(self):\n",
    "        return len(self.queue)\n",
    "\n",
    "# 使用示例\n",
    "queue = Queue()\n",
    "queue.enqueue('a')\n",
    "queue.enqueue('b')\n",
    "queue.enqueue('c')\n",
    "\n",
    "print(\"队首元素:\", queue.peek())    # 输出: 队首元素: a\n",
    "print(\"队列大小:\", queue.size())    # 输出: 队列大小: 3\n",
    "\n",
    "print(\"移除的元素:\", queue.dequeue())  # 输出: 移除的元素: a\n",
    "print(\"队列是否为空:\", queue.is_empty())  # 输出: 队列是否为空: False\n",
    "print(\"队列大小:\", queue.size())    # 输出: 队列大小: 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "fe3e2438-2b95-4e63-bffe-e692e484e3a9",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[6, 12, 18]"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 列表推导式\n",
    "\n",
    "vec = [2, 4, 6]\n",
    "[3*x for x in vec]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "a2506c85-463d-48e1-9faf-4a40f7d4605b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[[2, 4], [4, 16], [6, 36]]"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "[[x, x**2] for x in vec]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "a366a22c-f21e-40ae-8c84-f849b86a2fe6",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['banana', 'loganberry', 'passion fruit']"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "freshfruit = ['  banana', '  loganberry ', 'passion fruit  ']\n",
    "[weapon.strip() for weapon in freshfruit]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "e8f44f32-6bfb-4284-8d0a-2d6c723a2eba",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[12, 18]"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "[3*x for x in vec if x > 3]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "d35f73d4-f88d-4a02-867b-7d420ede6a38",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[]"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "[3*x for x in vec if x < 2]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "12fd34f7-dde6-4df5-bff1-1071d50c3db5",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[8, 6, -18, 16, 12, -36, 24, 18, -54]"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "vec1 = [2, 4, 6]\n",
    "vec2 = [4, 3, -9]\n",
    "[x*y for x in vec1 for y in vec2]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "f68b3ab6-9518-4778-ba92-88b61003a251",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[6, 5, -7, 8, 7, -5, 10, 9, -3]"
      ]
     },
     "execution_count": 35,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "[x+y for x in vec1 for y in vec2]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "156cd228-d8ab-46bf-b665-3ebc58e4493c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[8, 12, -54]"
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "[vec1[i]*vec2[i] for i in range(len(vec1))]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "338fd7c3-3813-418e-a35d-7d82011f72ae",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]"
      ]
     },
     "execution_count": 37,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "matrix = [\n",
    "    [1, 2, 3, 4],\n",
    "    [5, 6, 7, 8],\n",
    "    [9, 10, 11, 12],\n",
    "]\n",
    "[[row[i] for row in matrix] for i in range(4)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "27c7d261-cef8-4f85-b177-5a5d893bf3fb",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]"
      ]
     },
     "execution_count": 38,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "transposed = []\n",
    "for i in range(4):\n",
    "    transposed.append([row[i] for row in matrix])\n",
    "transposed"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "925e8c71-396b-4f38-afd6-bf8970ecc6c7",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "transposed = []\n",
    "for i in range(4):\n",
    "    transposed_row = []\n",
    "    for row in matrix:\n",
    "        transposed_row.append(row[i])\n",
    "    transposed.append(transposed_row)\n",
    "transposed"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "id": "77449ede-7155-4e83-9d43-61f6625d1c0a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 66.25, 333, 333, 1234.5]"
      ]
     },
     "execution_count": 40,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = [-1, 1, 66.25, 333, 333, 1234.5]\n",
    "del a[0]\n",
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "6172603c-7e84-4d70-b4d6-817cd0ddcb5f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 66.25, 1234.5]"
      ]
     },
     "execution_count": 41,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "del a[2:4]\n",
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "id": "838ce784-f078-4c0f-856c-20dc2b3084c4",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[]"
      ]
     },
     "execution_count": 42,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "del a[:]\n",
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "id": "39fde38e-c754-4b55-9e59-aa1424b5e8bc",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "What is your name?  It is lancelot.\n",
      "What is your quest?  It is the holy grail.\n",
      "What is your favorite color?  It is blue.\n"
     ]
    }
   ],
   "source": [
    "questions = ['name', 'quest', 'favorite color']\n",
    "answers = ['lancelot', 'the holy grail', 'blue']\n",
    "for q, a in zip(questions, answers):\n",
    "    print('What is your {0}?  It is {1}.'.format(q, a))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d7f460ff-a4c3-4124-9a67-40cee1abfdab",
   "metadata": {},
   "source": [
    "# Python标准的模块库\n",
    "\n",
    "|模块名|功能描述|\n",
    "|--|--|\n",
    "|math|数学运算（如平方根、三角函数等）|\n",
    "|os|操作系统相关功能（如文件、目录操作）|\n",
    "|sys|系统相关的参数和函数|\n",
    "|random|生成随机数|\n",
    "|datetime|处理日期和时间|\n",
    "|json|处理 JSON 数据|\n",
    "|re|正则表达式操作|\n",
    "|collections|提供额外的数据结构（如 defaultdict、deque）|\n",
    "|itertools|提供迭代器工具|\n",
    "|functools|高阶函数工具（如 reduce、lru_cache）|"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2b141bb1-e127-4e90-b46a-0b542e8e88e0",
   "metadata": {},
   "source": [
    "# File(文件) 方法\n",
    "\n",
    "`open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)`\n",
    "\n",
    "- file: 必需，文件路径（相对或者绝对路径）。\n",
    "- mode: 可选，文件打开模式\n",
    "- buffering: 设置缓冲\n",
    "- encoding: 一般使用utf8\n",
    "- errors: 报错级别\n",
    "- newline: 区分换行符\n",
    "- closefd: 传入的file参数类型\n",
    "- opener: 设置自定义开启器，开启器的返回值必须是一个打开的文件描述符。\n",
    "\n",
    "|模式|描述|\n",
    "|--|--|\n",
    "|t|文本模式 (默认)。|\n",
    "|x|写模式，新建一个文件，如果该文件已存在则会报错。|\n",
    "|b|二进制模式。|\n",
    "|+|打开一个文件进行更新(可读可写)。|\n",
    "|U|通用换行模式（Python 3 不支持）。|\n",
    "|r|以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。|\n",
    "|rb|以二进制格式打开一个文件用于只读。文件指针将会放在文件的开头。这是默认模式。一般用于非文本文件如图片等。|\n",
    "|r+|打开一个文件用于读写。文件指针将会放在文件的开头。|\n",
    "|rb+|以二进制格式打开一个文件用于读写。文件指针将会放在文件的开头。一般用于非文本文件如图片等。|\n",
    "|w|打开一个文件只用于写入。如果该文件已存在则打开文件，并从开头开始编辑，即原有内容会被删除。如果该文件不存在，创建新文件。|\n",
    "|wb|以二进制格式打开一个文件只用于写入。如果该文件已存在则打开文件，并从开头开始编辑，即原有内容会被删除。如果该文件不存在，创建新文件。一般用于非文本文件如图片等。|\n",
    "|w+|打开一个文件用于读写。如果该文件已存在则打开文件，并从开头开始编辑，即原有内容会被删除。如果该文件不存在，创建新文件。|\n",
    "|wb+|以二进制格式打开一个文件用于读写。如果该文件已存在则打开文件，并从开头开始编辑，即原有内容会被删除。如果该文件不存在，创建新文件。一般用于非文本文件如图片等。|\n",
    "|a|打开一个文件用于追加。如果该文件已存在，文件指针将会放在文件的结尾。也就是说，新的内容将会被写入到已有内容之后。如果该文件不存在，创建新文件进行写入。|\n",
    "|ab|以二进制格式打开一个文件用于追加。如果该文件已存在，文件指针将会放在文件的结尾。也就是说，新的内容将会被写入到已有内容之后。如果该文件不存在，创建新文件进行写入。|\n",
    "|a+|打开一个文件用于读写。如果该文件已存在，文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在，创建新文件用于读写。|\n",
    "|ab+|以二进制格式打开一个文件用于追加。如果该文件已存在，文件指针将会放在文件的结尾。如果该文件不存在，创建新文件用于读写。|\n",
    "\n",
    "|方法|描述|\n",
    "|--|--|\n",
    "|file.close()|关闭文件。关闭后文件不能再进行读写操作。|\n",
    "|file.flush()|刷新文件内部缓冲，直接把内部缓冲区的数据立刻写入文件, 而不是被动的等待输出缓冲区写入。|\n",
    "|file.fileno()|返回一个整型的文件描述符(file descriptor FD 整型), 可以用在如os模块的read方法等一些底层操作上。|\n",
    "|file.isatty()|如果文件连接到一个终端设备返回 True，否则返回 False。|\n",
    "|file.next()|Python 3 中的 File 对象不支持 next() 方法。返回文件下一行。|\n",
    "|file.read([size])|从文件读取指定的字节数，如果未给定或为负则读取所有。|\n",
    "|file.readline([size])|读取整行，包括 \"\\n\" 字符。|\n",
    "|file.readlines([sizeint])|读取所有行并返回列表，若给定sizeint>0，返回总和大约为sizeint字节的行, 实际读取值可能比 sizeint 较大, 因为需要填充缓冲区。|\n",
    "|file.seek(offset[, whence])|移动文件读取指针到指定位置|\n",
    "|file.tell()|返回文件当前位置。|\n",
    "|file.truncate([size])|从文件的首行首字符开始截断，截断文件为 size 个字符，无 size 表示从当前位置截断；截断之后后面的所有字符被删除，其中 windows 系统下的换行代表2个字符大小。|\n",
    "|file.write(str)|将字符串写入文件，返回的是写入的字符长度。|\n",
    "|file.writelines(sequence)|向文件写入一个序列字符串列表，如果需要换行则要自己加入每行的换行符。|"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f2490a2a-2a8c-4e92-b512-9ec8a717dd05",
   "metadata": {},
   "source": [
    "# OS 文件/目录方法\n",
    "\n",
    "|方法|描述|\n",
    "|--|--|\n",
    "|os.access(path, mode)|检验权限模式|\n",
    "|os.chdir(path)|改变当前工作目录|\n",
    "|os.chflags(path, flags)|设置路径的标记为数字标记。|\n",
    "|os.chmod(path, mode)|更改权限|\n",
    "|os.chown(path, uid, gid)|更改文件所有者|\n",
    "|os.chroot(path)|改变当前进程的根目录|\n",
    "|os.close(fd)|关闭文件描述符 fd|\n",
    "|os.closerange(fd_low, fd_high)|关闭所有文件描述符，从 fd_low (包含) 到 fd_high (不包含), 错误会忽略|\n",
    "|os.dup(fd)|复制文件描述符 fd|\n",
    "|os.dup2(fd, fd2)|将一个文件描述符 fd 复制到另一个 fd2|\n",
    "|os.fchdir(fd)|通过文件描述符改变当前工作目录|\n",
    "|os.fchmod(fd, mode)|改变一个文件的访问权限，该文件由参数fd指定，参数mode是Unix下的文件访问权限。|\n",
    "|os.fchown(fd, uid, gid)|修改一个文件的所有权，这个函数修改一个文件的用户ID和用户组ID，该文件由文件描述符fd指定。|\n",
    "|os.fdatasync(fd)|强制将文件写入磁盘，该文件由文件描述符fd指定，但是不强制更新文件的状态信息。|\n",
    "|os.fdopen(fd[, mode[, bufsize]])|通过文件描述符 fd 创建一个文件对象，并返回这个文件对象|\n",
    "|os.fpathconf(fd, name)|返回一个打开的文件的系统配置信息。name为检索的系统配置的值，它也许是一个定义系统值的字符串，这些名字在很多标准中指定（POSIX.1, Unix 95, Unix 98, 和其它）。|\n",
    "|os.fstat(fd)|返回文件描述符fd的状态，像stat()。|\n",
    "|os.fstatvfs(fd)|返回包含文件描述符fd的文件的文件系统的信息，Python 3.3 相等于 statvfs()。|\n",
    "|os.fsync(fd)|强制将文件描述符为fd的文件写入硬盘。|\n",
    "|os.ftruncate(fd, length)|裁剪文件描述符fd对应的文件, 所以它最大不能超过文件大小。|\n",
    "|os.getcwd()|返回当前工作目录|\n",
    "|os.getcwdb()|返回一个当前工作目录的Unicode对象|\n",
    "|os.isatty(fd)|如果文件描述符fd是打开的，同时与tty(-like)设备相连，则返回true, 否则False。|\n",
    "|os.lchflags(path, flags)|设置路径的标记为数字标记，类似 chflags()，但是没有软链接|\n",
    "|os.lchmod(path, mode)|修改连接文件权限|\n",
    "|os.lchown(path, uid, gid)|更改文件所有者，类似 chown，但是不追踪链接。|\n",
    "|os.link(src, dst)|创建硬链接，名为参数 dst，指向参数 src|\n",
    "|os.listdir(path)|返回path指定的文件夹包含的文件或文件夹的名字的列表。|\n",
    "|os.lseek(fd, pos, how)|设置文件描述符 fd当前位置为pos, how方式修改: SEEK_SET 或者 0 设置从文件开始的计算的pos; SEEK_CUR或者 1 则从当前位置计算; os.SEEK_END或者2则从文件尾部开始. 在unix，Windows中有效|\n",
    "|os.lstat(path)|像stat(),但是没有软链接|\n",
    "|os.major(device)|从原始的设备号中提取设备major号码 (使用stat中的st_dev或者st_rdev field)。|\n",
    "|os.makedev(major, minor)|以major和minor设备号组成一个原始设备号|\n",
    "|os.makedirs(path[, mode])|递归文件夹创建函数。像mkdir(), 但创建的所有intermediate-level文件夹需要包含子文件夹。|\n",
    "|os.minor(device)|从原始的设备号中提取设备minor号码 (使用stat中的st_dev或者st_rdev field )。|\n",
    "|os.mkdir(path[, mode])|以数字mode的mode创建一个名为path的文件夹.默认的 mode 是 0777 (八进制)。|\n",
    "|os.mkfifo(path[, mode])|创建命名管道，mode 为数字，默认为 0666 (八进制)|\n",
    "|os.mknod(filename[, mode=0600, device])|创建一个名为filename文件系统节点（文件，设备特别文件或者命名pipe）。|\n",
    "|os.open(file, flags[, mode])|打开一个文件，并且设置需要的打开选项，mode参数是可选的|\n",
    "|os.openpty()|打开一个新的伪终端对。返回 pty 和 tty的文件描述符。|\n",
    "|os.pathconf(path, name)|返回相关文件的系统配置信息。|\n",
    "|os.pipe()|创建一个管道. 返回一对文件描述符(r, w) 分别为读和写|\n",
    "|os.popen(command[, mode[, bufsize]])|从一个 command 打开一个管道|\n",
    "|os.read(fd, n)|从文件描述符 fd 中读取最多 n 个字节，返回包含读取字节的字符串，文件描述符 fd对应文件已达到结尾, 返回一个空字符串。|\n",
    "|os.readlink(path)|返回软链接所指向的文件|\n",
    "|os.remove(path)|删除路径为path的文件。如果path 是一个文件夹，将抛出OSError; 查看下面的rmdir()删除一个 directory。|\n",
    "|os.removedirs(path)|递归删除目录。|\n",
    "|os.rename(src, dst)|重命名文件或目录，从 src 到 dst|\n",
    "|os.renames(old, new)|递归地对目录进行更名，也可以对文件进行更名。|\n",
    "|os.rmdir(path)|删除path指定的空目录，如果目录非空，则抛出一个OSError异常。|\n",
    "|os.stat(path)|获取path指定的路径的信息，功能等同于C API中的stat()系统调用。|\n",
    "|os.stat_float_times([newvalue])|决定stat_result是否以float对象显示时间戳|\n",
    "|os.statvfs(path)|获取指定路径的文件系统统计信息|\n",
    "|os.symlink(src, dst)|创建一个软链接|\n",
    "|os.tcgetpgrp(fd)|返回与终端fd（一个由os.open()返回的打开的文件描述符）关联的进程组|\n",
    "|os.tcsetpgrp(fd, pg)|设置与终端fd（一个由os.open()返回的打开的文件描述符）关联的进程组为pg。|\n",
    "|os.ttyname(fd)|返回一个字符串，它表示与文件描述符fd 关联的终端设备。如果fd 没有与终端设备关联，则引发一个异常。|\n",
    "|os.unlink(path)|删除文件路径|\n",
    "|os.utime(path, times)|返回指定的path文件的访问和修改的时间。|\n",
    "|os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])|输出在文件夹中的文件名通过在树中游走，向上或者向下。|\n",
    "|os.write(fd, str)|写入字符串到文件描述符 fd中. 返回实际写入的字符串长度|\n",
    "|os.path 模块|获取文件的属性信息。|\n",
    "|os.pardir()|获取当前目录的父目录，以字符串形式显示目录名。|\n",
    "|os.replace()|重命名文件或目录。|\n",
    "|os.startfile()|用于在 Windows 上打开一个文件或文件夹。|"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "id": "e808fd8b-2145-4d9b-89e2-a71812097dcb",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "OS error: [Errno 2] No such file or directory: 'myfile.txt'\n",
      "这句话，无论异常是否发生都会执行。\n"
     ]
    }
   ],
   "source": [
    "import sys\n",
    "\n",
    "try:\n",
    "    f = open('myfile.txt')\n",
    "    s = f.readline()\n",
    "    i = int(s.strip())\n",
    "except OSError as err:\n",
    "    print(\"OS error: {0}\".format(err))\n",
    "except ValueError:\n",
    "    print(\"Could not convert data to an integer.\")\n",
    "except:\n",
    "    print(\"Unexpected error:\", sys.exc_info()[0])\n",
    "    raise\n",
    "finally:\n",
    "    print('这句话，无论异常是否发生都会执行。')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "d53133d1-0a10-42b7-beb2-9eb01faa1633",
   "metadata": {},
   "outputs": [
    {
     "ename": "Exception",
     "evalue": "x 不能大于 5。x 的值为: 10",
     "output_type": "error",
     "traceback": [
      "\u001b[31m---------------------------------------------------------------------------\u001b[39m",
      "\u001b[31mException\u001b[39m                                 Traceback (most recent call last)",
      "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[45]\u001b[39m\u001b[32m, line 3\u001b[39m\n\u001b[32m      1\u001b[39m x = \u001b[32m10\u001b[39m\n\u001b[32m      2\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m x > \u001b[32m5\u001b[39m:\n\u001b[32m----> \u001b[39m\u001b[32m3\u001b[39m     \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mException\u001b[39;00m(\u001b[33m'\u001b[39m\u001b[33mx 不能大于 5。x 的值为: \u001b[39m\u001b[38;5;132;01m{}\u001b[39;00m\u001b[33m'\u001b[39m.format(x))\n",
      "\u001b[31mException\u001b[39m: x 不能大于 5。x 的值为: 10"
     ]
    }
   ],
   "source": [
    "x = 10\n",
    "if x > 5:\n",
    "    raise Exception('x 不能大于 5。x 的值为: {}'.format(x))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "90eb34f3-0dcd-4a11-bf00-3ba23630c608",
   "metadata": {},
   "outputs": [],
   "source": [
    "class Error(Exception):\n",
    "    \"\"\"Base class for exceptions in this module.\"\"\"\n",
    "    pass\n",
    "\n",
    "class InputError(Error):\n",
    "    \"\"\"Exception raised for errors in the input.\n",
    "\n",
    "    Attributes:\n",
    "        expression -- input expression in which the error occurred\n",
    "        message -- explanation of the error\n",
    "    \"\"\"\n",
    "\n",
    "    def __init__(self, expression, message):\n",
    "        self.expression = expression\n",
    "        self.message = message\n",
    "\n",
    "class TransitionError(Error):\n",
    "    \"\"\"Raised when an operation attempts a state transition that's not\n",
    "    allowed.\n",
    "\n",
    "    Attributes:\n",
    "        previous -- state at beginning of transition\n",
    "        next -- attempted new state\n",
    "        message -- explanation of why the specific transition is not allowed\n",
    "    \"\"\"\n",
    "\n",
    "    def __init__(self, previous, next, message):\n",
    "        self.previous = previous\n",
    "        self.next = next\n",
    "        self.message = message"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a3058c8c-2145-4105-af60-64756316de14",
   "metadata": {},
   "outputs": [],
   "source": [
    "#类定义\n",
    "class people:\n",
    "    #定义基本属性\n",
    "    name = ''\n",
    "    age = 0\n",
    "    #定义私有属性,私有属性在类外部无法直接进行访问\n",
    "    __weight = 0\n",
    "    #定义构造方法\n",
    "    def __init__(self,n,a,w):\n",
    "        self.name = n\n",
    "        self.age = a\n",
    "        self.__weight = w\n",
    "    def speak(self):\n",
    "        print(\"%s 说: 我 %d 岁。\" %(self.name,self.age))\n",
    "\n",
    "#单继承示例\n",
    "class student(people):\n",
    "    grade = ''\n",
    "    def __init__(self,n,a,w,g):\n",
    "        #调用父类的构函\n",
    "        people.__init__(self,n,a,w)\n",
    "        self.grade = g\n",
    "    #覆写父类的方法\n",
    "    def speak(self):\n",
    "        print(\"%s 说: 我 %d 岁了，我在读 %d 年级\"%(self.name,self.age,self.grade))\n",
    "\n",
    "s = student('ken',10,60,3)\n",
    "s.speak()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d0808c85-7374-4cdb-8855-159d653b0b34",
   "metadata": {},
   "outputs": [],
   "source": [
    "#类定义\n",
    "class people:\n",
    "    #定义基本属性\n",
    "    name = ''\n",
    "    age = 0\n",
    "    #定义私有属性,私有属性在类外部无法直接进行访问\n",
    "    __weight = 0\n",
    "    #定义构造方法\n",
    "    def __init__(self,n,a,w):\n",
    "        self.name = n\n",
    "        self.age = a\n",
    "        self.__weight = w\n",
    "    def speak(self):\n",
    "        print(\"%s 说: 我 %d 岁。\" %(self.name,self.age))\n",
    "\n",
    "#单继承示例\n",
    "class student(people):\n",
    "    grade = ''\n",
    "    def __init__(self,n,a,w,g):\n",
    "        #调用父类的构函\n",
    "        people.__init__(self,n,a,w)\n",
    "        self.grade = g\n",
    "    #覆写父类的方法\n",
    "    def speak(self):\n",
    "        print(\"%s 说: 我 %d 岁了，我在读 %d 年级\"%(self.name,self.age,self.grade))\n",
    "\n",
    "#另一个类，多继承之前的准备\n",
    "class speaker():\n",
    "    topic = ''\n",
    "    name = ''\n",
    "    def __init__(self,n,t):\n",
    "        self.name = n\n",
    "        self.topic = t\n",
    "    def speak(self):\n",
    "        print(\"我叫 %s，我是一个演说家，我演讲的主题是 %s\"%(self.name,self.topic))\n",
    "\n",
    "#多继承\n",
    "class sample(speaker,student):\n",
    "    a =''\n",
    "    def __init__(self,n,a,w,g,t):\n",
    "        student.__init__(self,n,a,w,g)\n",
    "        speaker.__init__(self,n,t)\n",
    "\n",
    "test = sample(\"Tim\",25,80,4,\"Python\")\n",
    "test.speak()   #方法名同，默认调用的是在括号中参数位置排前父类的方法"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b3d36d2b-7c9d-4c6b-b956-473a9148b857",
   "metadata": {},
   "source": [
    "# 类的专有方法：\n",
    "\n",
    "```\n",
    "__init__ : 构造函数，在生成对象时调用\n",
    "__del__ : 析构函数，释放对象时使用\n",
    "__repr__ : 打印，转换\n",
    "__setitem__ : 按照索引赋值\n",
    "__getitem__: 按照索引获取值\n",
    "__len__: 获得长度\n",
    "__cmp__: 比较运算\n",
    "__call__: 函数调用\n",
    "__add__: 加运算\n",
    "__sub__: 减运算\n",
    "__mul__: 乘运算\n",
    "__truediv__: 除运算\n",
    "__mod__: 求余运算\n",
    "__pow__: 乘方\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "603e109b-b3c9-46e4-a29d-59a911643f6b",
   "metadata": {},
   "source": [
    "# 正则表达式\n",
    "\n",
    "|模式|描述|\n",
    "|--|--|\n",
    "|^|匹配字符串的开头|\n",
    "|$|匹配字符串的末尾。|\n",
    "|.|匹配任意字符，除了换行符，当re.DOTALL标记被指定时，则可以匹配包括换行符的任意字符。|\n",
    "|[...]|用来匹配所包含的任意一个字符，例如 [amk] 匹配 'a'，'m'或'k'|\n",
    "|[^...]|不在[]中的字符：[^abc] 匹配除了a,b,c之外的字符。|\n",
    "|re*|匹配0个或多个的表达式。|\n",
    "|re+|匹配1个或多个的表达式。|\n",
    "|re?|匹配0个或1个由前面的正则表达式定义的片段，非贪婪方式|\n",
    "|re{ n}|匹配n个前面表达式。例如，\"o{2}\"不能匹配\"Bob\"中的\"o\"，但是能匹配\"food\"中的两个o。|\n",
    "|re{ n,}|精确匹配n个前面表达式。例如，\"o{2,}\"不能匹配\"Bob\"中的\"o\"，但能匹配\"foooood\"中的所有o。\"o{1,}\"等价于\"o+\"。\"o{0,}\"则等价于\"o*\"。|\n",
    "|re{ n, m}|匹配 n 到 m 次由前面的正则表达式定义的片段，贪婪方式|\n",
    "|a\\| b|匹配a或b|\n",
    "|(re)|匹配括号内的表达式，也表示一个组|\n",
    "|(?imx)|正则表达式包含三种可选标志：i, m, 或 x 。只影响括号中的区域。|\n",
    "|(?-imx)|正则表达式关闭 i, m, 或 x 可选标志。只影响括号中的区域。|\n",
    "|(?: re)|类似 (...), 但是不表示一个组|\n",
    "|(?imx: re)|在括号中使用i, m, 或 x 可选标志|\n",
    "|(?-imx: re)|在括号中不使用i, m, 或 x 可选标志|\n",
    "|(?#...)|注释.|\n",
    "|(?= re)|前向肯定界定符。如果所含正则表达式，以 ... 表示，在当前位置成功匹配时成功，否则失败。但一旦所含表达式已经尝试，匹配引擎根本没有提高；模式的剩余部分还要尝试界定符的右边。|\n",
    "|(?! re)|前向否定界定符。与肯定界定符相反；当所含表达式不能在字符串当前位置匹配时成功。|\n",
    "|(?> re)|匹配的独立模式，省去回溯。|\n",
    "|\\w|匹配数字字母下划线|\n",
    "|\\W|匹配非数字字母下划线|\n",
    "|\\s|匹配任意空白字符，等价于 [\\t\\n\\r\\f]。|\n",
    "|\\S|匹配任意非空字符|\n",
    "|\\d|匹配任意数字，等价于 [0-9]。|\n",
    "|\\D|匹配任意非数字|\n",
    "|\\A|匹配字符串开始|\n",
    "|\\Z|匹配字符串结束，如果是存在换行，只匹配到换行前的结束字符串。|\n",
    "|\\z|匹配字符串结束|\n",
    "|\\G|匹配最后匹配完成的位置。|\n",
    "|\\b|匹配一个单词边界，也就是指单词和空格间的位置。例如， 'er\\b' 可以匹配\"never\" 中的 'er'，但不能匹配 \"verb\" 中的 'er'。|\n",
    "|\\B|匹配非单词边界。'er\\B' 能匹配 \"verb\" 中的 'er'，但不能匹配 \"never\" 中的 'er'。|\n",
    "|\\n, \\t, 等。|匹配一个换行符。匹配一个制表符, 等|\n",
    "|\\1...\\9|匹配第n个分组的内容。|\n",
    "|\\10|匹配第n个分组的内容，如果它经匹配。否则指的是八进制字符码的表达式。|"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "029a37fa-f33c-4679-a70e-6b874101179c",
   "metadata": {},
   "source": [
    "# Socket 对象(内建)方法\n",
    "\n",
    "|函数|描述|\n",
    "|--|--|\n",
    "|服务器端套接字||\n",
    "|s.bind()|绑定地址（host,port）到套接字， 在AF_INET下,以元组（host,port）的形式表示地址。|\n",
    "|s.listen()|开始TCP监听。backlog指定在拒绝连接之前，操作系统可以挂起的最大连接数量。该值至少为1，大部分应用程序设为5就可以了。|\n",
    "|s.accept()|被动接受TCP客户端连接,(阻塞式)等待连接的到来|\n",
    "|客户端套接字||\n",
    "|s.connect()|主动初始化TCP服务器连接，。一般address的格式为元组（hostname,port），如果连接出错，返回socket.error错误。|\n",
    "|s.connect_ex()|connect()函数的扩展版本,出错时返回出错码,而不是抛出异常|\n",
    "|公共用途的套接字函数||\n",
    "|s.recv()|接收TCP数据，数据以字符串形式返回，bufsize指定要接收的最大数据量。flag提供有关消息的其他信息，通常可以忽略。|\n",
    "|s.send()|发送TCP数据，将string中的数据发送到连接的套接字。返回值是要发送的字节数量，该数量可能小于string的字节大小。|\n",
    "|s.sendall()|完整发送TCP数据。将string中的数据发送到连接的套接字，但在返回之前会尝试发送所有数据。成功返回None，失败则抛出异常。|\n",
    "|s.recvfrom()|接收UDP数据，与recv()类似，但返回值是（data,address）。其中data是包含接收数据的字符串，address是发送数据的套接字地址。|\n",
    "|s.sendto()|发送UDP数据，将数据发送到套接字，address是形式为（ipaddr，port）的元组，指定远程地址。返回值是发送的字节数。|\n",
    "|s.close()|关闭套接字|\n",
    "|s.getpeername()|返回连接套接字的远程地址。返回值通常是元组（ipaddr,port）。|\n",
    "|s.getsockname()|返回套接字自己的地址。通常是一个元组(ipaddr,port)|\n",
    "|s.setsockopt(level,optname,value)|设置给定套接字选项的值。|\n",
    "|s.getsockopt(level,optname[.buflen])|返回套接字选项的值。|\n",
    "|s.settimeout(timeout)|设置套接字操作的超时期，timeout是一个浮点数，单位是秒。值为None表示没有超时期。一般，超时期应该在刚创建套接字时设置，因为它们可能用于连接的操作（如connect()）|\n",
    "|s.gettimeout()|返回当前超时期的值，单位是秒，如果没有设置超时期，则返回None。|\n",
    "|s.fileno()|返回套接字的文件描述符。|\n",
    "|s.setblocking(flag)|如果 flag 为 False，则将套接字设为非阻塞模式，否则将套接字设为阻塞模式（默认值）。非阻塞模式下，如果调用 recv() 没有发现任何数据，或 send() 调用无法立即发送数据，那么将引起 socket.error 异常。|\n",
    "|s.makefile()|创建一个与该套接字相关连的文件|"
   ]
  },
  {
   "cell_type": "raw",
   "id": "c1ff1039-3b79-4649-a740-855d9578a092",
   "metadata": {},
   "source": [
    "# 导入 socket、sys 模块\n",
    "import socket\n",
    "import sys\n",
    "\n",
    "# 创建 socket 对象\n",
    "serversocket = socket.socket(\n",
    "            socket.AF_INET, socket.SOCK_STREAM) \n",
    "\n",
    "# 获取本地主机名\n",
    "host = socket.gethostname()\n",
    "\n",
    "port = 9999\n",
    "\n",
    "# 绑定端口号\n",
    "serversocket.bind((host, port))\n",
    "\n",
    "# 设置最大连接数，超过后排队\n",
    "serversocket.listen(5)\n",
    "\n",
    "while True:\n",
    "    # 建立客户端连接\n",
    "    clientsocket,addr = serversocket.accept()      \n",
    "\n",
    "    print(\"连接地址: %s\" % str(addr))\n",
    "    \n",
    "    msg='欢迎访问菜鸟教程！'+ \"\\r\\n\"\n",
    "    clientsocket.send(msg.encode('utf-8'))\n",
    "    clientsocket.close()"
   ]
  },
  {
   "cell_type": "raw",
   "id": "c40fef92-205a-4fdc-b7d7-f81309a58ebd",
   "metadata": {},
   "source": [
    "# 导入 socket、sys 模块\n",
    "import socket\n",
    "import sys\n",
    "\n",
    "# 创建 socket 对象\n",
    "s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) \n",
    "\n",
    "# 获取本地主机名\n",
    "host = socket.gethostname() \n",
    "\n",
    "# 设置端口号\n",
    "port = 9999\n",
    "\n",
    "# 连接服务，指定主机和端口\n",
    "s.connect((host, port))\n",
    "\n",
    "# 接收小于 1024 字节的数据\n",
    "msg = s.recv(1024)\n",
    "\n",
    "s.close()\n",
    "\n",
    "print (msg.decode('utf-8'))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "feda1712-eb15-4005-80cc-7596b31ae297",
   "metadata": {},
   "source": [
    "# Internet 模块\n",
    "\n",
    "|协议|功能用处|端口号|Python 模块|\n",
    "|--|--|--|--|\n",
    "|HTTP|网页访问|80|httplib, urllib, xmlrpclib|\n",
    "|NNTP|阅读和张贴新闻文章，俗称为\"帖子\"|119|nntplib|\n",
    "|FTP|文件传输|20|ftplib, urllib|\n",
    "|SMTP|发送邮件|25|smtplib|\n",
    "|POP3|接收邮件|110|poplib|\n",
    "|IMAP4|获取邮件|143|imaplib|\n",
    "|Telnet|命令行|23|telnetlib|\n",
    "|Gopher|信息查找|70|gopherlib, urllib|"
   ]
  },
  {
   "cell_type": "raw",
   "id": "1a41a6fa-212e-4601-8f6b-75c2ba2bb21f",
   "metadata": {},
   "source": [
    "import smtplib\n",
    "from email.mime.text import MIMEText\n",
    "from email.header import Header\n",
    " \n",
    "sender = 'from@runoob.com'\n",
    "receivers = ['429240967@qq.com']  # 接收邮件，可设置为你的QQ邮箱或者其他邮箱\n",
    " \n",
    "# 三个参数：第一个为文本内容，第二个 plain 设置文本格式，第三个 utf-8 设置编码\n",
    "message = MIMEText('Python 邮件发送测试...', 'plain', 'utf-8')\n",
    "message['From'] = Header(\"菜鸟教程\", 'utf-8')     # 发送者\n",
    "message['To'] =  Header(\"测试\", 'utf-8')          # 接收者\n",
    " \n",
    "subject = 'Python SMTP 邮件测试'\n",
    "message['Subject'] = Header(subject, 'utf-8')\n",
    " \n",
    " \n",
    "try:\n",
    "    smtpObj = smtplib.SMTP('localhost')\n",
    "    smtpObj.sendmail(sender, receivers, message.as_string())\n",
    "    print (\"邮件发送成功\")\n",
    "except smtplib.SMTPException:\n",
    "    print (\"Error: 无法发送邮件\")"
   ]
  },
  {
   "cell_type": "raw",
   "id": "3cbecf54-8380-4afd-bb61-31a7ca092b12",
   "metadata": {},
   "source": [
    "import smtplib\n",
    "from email.mime.text import MIMEText\n",
    "from email.header import Header\n",
    " \n",
    "# 第三方 SMTP 服务\n",
    "mail_host=\"smtp.XXX.com\"  #设置服务器\n",
    "mail_user=\"XXXX\"    #用户名\n",
    "mail_pass=\"XXXXXX\"   #口令 \n",
    " \n",
    " \n",
    "sender = 'from@runoob.com'\n",
    "receivers = ['429240967@qq.com']  # 接收邮件，可设置为你的QQ邮箱或者其他邮箱\n",
    " \n",
    "message = MIMEText('Python 邮件发送测试...', 'plain', 'utf-8')\n",
    "message['From'] = Header(\"菜鸟教程\", 'utf-8')\n",
    "message['To'] =  Header(\"测试\", 'utf-8')\n",
    " \n",
    "subject = 'Python SMTP 邮件测试'\n",
    "message['Subject'] = Header(subject, 'utf-8')\n",
    " \n",
    " \n",
    "try:\n",
    "    smtpObj = smtplib.SMTP() \n",
    "    smtpObj.connect(mail_host, 25)    # 25 为 SMTP 端口号\n",
    "    smtpObj.login(mail_user,mail_pass)\n",
    "    smtpObj.sendmail(sender, receivers, message.as_string())\n",
    "    print (\"邮件发送成功\")\n",
    "except smtplib.SMTPException:\n",
    "    print (\"Error: 无法发送邮件\")"
   ]
  },
  {
   "cell_type": "raw",
   "id": "88f9fcfb-8890-4b3f-a026-843c63b85916",
   "metadata": {},
   "source": [
    "import smtplib\n",
    "from email.mime.text import MIMEText\n",
    "from email.header import Header\n",
    " \n",
    "sender = 'from@runoob.com'\n",
    "receivers = ['429240967@qq.com']  # 接收邮件，可设置为你的QQ邮箱或者其他邮箱\n",
    " \n",
    "mail_msg = \"\"\"\n",
    "<p>Python 邮件发送测试...</p>\n",
    "<p><a href=\"http://www.runoob.com\">这是一个链接</a></p>\n",
    "\"\"\"\n",
    "message = MIMEText(mail_msg, 'html', 'utf-8')\n",
    "message['From'] = Header(\"菜鸟教程\", 'utf-8')\n",
    "message['To'] =  Header(\"测试\", 'utf-8')\n",
    " \n",
    "subject = 'Python SMTP 邮件测试'\n",
    "message['Subject'] = Header(subject, 'utf-8')\n",
    " \n",
    " \n",
    "try:\n",
    "    smtpObj = smtplib.SMTP('localhost')\n",
    "    smtpObj.sendmail(sender, receivers, message.as_string())\n",
    "    print (\"邮件发送成功\")\n",
    "except smtplib.SMTPException:\n",
    "    print (\"Error: 无法发送邮件\")"
   ]
  },
  {
   "cell_type": "raw",
   "id": "dcfc5d0e-9f95-4a66-9648-3f572e4b9197",
   "metadata": {},
   "source": [
    "import smtplib\n",
    "from email.mime.text import MIMEText\n",
    "from email.mime.multipart import MIMEMultipart\n",
    "from email.header import Header\n",
    " \n",
    "sender = 'from@runoob.com'\n",
    "receivers = ['429240967@qq.com']  # 接收邮件，可设置为你的QQ邮箱或者其他邮箱\n",
    " \n",
    "#创建一个带附件的实例\n",
    "message = MIMEMultipart()\n",
    "message['From'] = Header(\"菜鸟教程\", 'utf-8')\n",
    "message['To'] =  Header(\"测试\", 'utf-8')\n",
    "subject = 'Python SMTP 邮件测试'\n",
    "message['Subject'] = Header(subject, 'utf-8')\n",
    " \n",
    "#邮件正文内容\n",
    "message.attach(MIMEText('这是菜鸟教程Python 邮件发送测试……', 'plain', 'utf-8'))\n",
    " \n",
    "# 构造附件1，传送当前目录下的 test.txt 文件\n",
    "att1 = MIMEText(open('test.txt', 'rb').read(), 'base64', 'utf-8')\n",
    "att1[\"Content-Type\"] = 'application/octet-stream'\n",
    "# 这里的filename可以任意写，写什么名字，邮件中显示什么名字\n",
    "att1[\"Content-Disposition\"] = 'attachment; filename=\"test.txt\"'\n",
    "message.attach(att1)\n",
    " \n",
    "# 构造附件2，传送当前目录下的 runoob.txt 文件\n",
    "att2 = MIMEText(open('runoob.txt', 'rb').read(), 'base64', 'utf-8')\n",
    "att2[\"Content-Type\"] = 'application/octet-stream'\n",
    "att2[\"Content-Disposition\"] = 'attachment; filename=\"runoob.txt\"'\n",
    "message.attach(att2)\n",
    " \n",
    "try:\n",
    "    smtpObj = smtplib.SMTP('localhost')\n",
    "    smtpObj.sendmail(sender, receivers, message.as_string())\n",
    "    print (\"邮件发送成功\")\n",
    "except smtplib.SMTPException:\n",
    "    print (\"Error: 无法发送邮件\")"
   ]
  },
  {
   "cell_type": "raw",
   "id": "46e52452-e9b0-45d2-bf4f-59afa459bbcd",
   "metadata": {},
   "source": [
    "import smtplib\n",
    "from email.mime.image import MIMEImage\n",
    "from email.mime.multipart import MIMEMultipart\n",
    "from email.mime.text import MIMEText\n",
    "from email.header import Header\n",
    " \n",
    "sender = 'from@runoob.com'\n",
    "receivers = ['429240967@qq.com']  # 接收邮件，可设置为你的QQ邮箱或者其他邮箱\n",
    " \n",
    "msgRoot = MIMEMultipart('related')\n",
    "msgRoot['From'] = Header(\"菜鸟教程\", 'utf-8')\n",
    "msgRoot['To'] =  Header(\"测试\", 'utf-8')\n",
    "subject = 'Python SMTP 邮件测试'\n",
    "msgRoot['Subject'] = Header(subject, 'utf-8')\n",
    " \n",
    "msgAlternative = MIMEMultipart('alternative')\n",
    "msgRoot.attach(msgAlternative)\n",
    " \n",
    " \n",
    "mail_msg = \"\"\"\n",
    "<p>Python 邮件发送测试...</p>\n",
    "<p><a href=\"http://www.runoob.com\">菜鸟教程链接</a></p>\n",
    "<p>图片演示：</p>\n",
    "<p><img src=\"cid:image1\"></p>\n",
    "\"\"\"\n",
    "msgAlternative.attach(MIMEText(mail_msg, 'html', 'utf-8'))\n",
    " \n",
    "# 指定图片为当前目录\n",
    "fp = open('test.png', 'rb')\n",
    "msgImage = MIMEImage(fp.read())\n",
    "fp.close()\n",
    " \n",
    "# 定义图片 ID，在 HTML 文本中引用\n",
    "msgImage.add_header('Content-ID', '<image1>')\n",
    "msgRoot.attach(msgImage)\n",
    " \n",
    "try:\n",
    "    smtpObj = smtplib.SMTP('localhost')\n",
    "    smtpObj.sendmail(sender, receivers, msgRoot.as_string())\n",
    "    print (\"邮件发送成功\")\n",
    "except smtplib.SMTPException:\n",
    "    print (\"Error: 无法发送邮件\")"
   ]
  },
  {
   "cell_type": "raw",
   "id": "ad5e2a20-4e6a-4df7-82f6-13977db10f8b",
   "metadata": {},
   "source": [
    "import smtplib\n",
    "from email.mime.text import MIMEText\n",
    "from email.utils import formataddr\n",
    " \n",
    "my_sender='429240967@qq.com'    # 发件人邮箱账号\n",
    "my_pass = 'xxxxxxxxxx'              # 发件人邮箱密码\n",
    "my_user='429240967@qq.com'      # 收件人邮箱账号，我这边发送给自己\n",
    "def mail():\n",
    "    ret=True\n",
    "    try:\n",
    "        msg=MIMEText('填写邮件内容','plain','utf-8')\n",
    "        msg['From']=formataddr([\"FromRunoob\",my_sender])  # 括号里的对应发件人邮箱昵称、发件人邮箱账号\n",
    "        msg['To']=formataddr([\"FK\",my_user])              # 括号里的对应收件人邮箱昵称、收件人邮箱账号\n",
    "        msg['Subject']=\"菜鸟教程发送邮件测试\"                # 邮件的主题，也可以说是标题\n",
    " \n",
    "        server=smtplib.SMTP_SSL(\"smtp.qq.com\", 465)  # 发件人邮箱中的SMTP服务器，端口是25\n",
    "        server.login(my_sender, my_pass)  # 括号中对应的是发件人邮箱账号、邮箱密码\n",
    "        server.sendmail(my_sender,[my_user,],msg.as_string())  # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件\n",
    "        server.quit()  # 关闭连接\n",
    "    except Exception:  # 如果 try 中的语句没有执行，则会执行下面的 ret=False\n",
    "        ret=False\n",
    "    return ret\n",
    " \n",
    "ret=mail()\n",
    "if ret:\n",
    "    print(\"邮件发送成功\")\n",
    "else:\n",
    "    print(\"邮件发送失败\")"
   ]
  },
  {
   "cell_type": "raw",
   "id": "9b08d1a1-0036-498a-8a88-0cf3068ada4f",
   "metadata": {},
   "source": [
    "import _thread\n",
    "import time\n",
    "\n",
    "# 为线程定义一个函数\n",
    "def print_time( threadName, delay):\n",
    "   count = 0\n",
    "   while count < 5:\n",
    "      time.sleep(delay)\n",
    "      count += 1\n",
    "      print (\"%s: %s\" % ( threadName, time.ctime(time.time()) ))\n",
    "\n",
    "# 创建两个线程\n",
    "try:\n",
    "   _thread.start_new_thread( print_time, (\"Thread-1\", 2, ) )\n",
    "   _thread.start_new_thread( print_time, (\"Thread-2\", 4, ) )\n",
    "except:\n",
    "   print (\"Error: 无法启动线程\")\n",
    "\n",
    "while 1:\n",
    "   pass"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "85031e40-7bca-41ac-b8f4-dbe78ff2e117",
   "metadata": {},
   "source": [
    "# threading.Thread\n",
    "\n",
    "- __init__(self, group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)：初始化Thread对象。\n",
    "- group：线程组，暂时未使用，保留为将来的扩展。\n",
    "- target：线程将要执行的目标函数。\n",
    "- name：线程的名称。\n",
    "- args：目标函数的参数，以元组形式传递。\n",
    "- kwargs：目标函数的关键字参数，以字典形式传递。\n",
    "- daemon：指定线程是否为守护线程。\n",
    "- start(self)：启动线程。将调用线程的run()方法。\n",
    "- run(self)：线程在此方法中定义要执行的代码。\n",
    "- join(self, timeout=None)：等待线程终止。默认情况下，join()会一直阻塞，直到被调用线程终止。如果指定了timeout参数，则最多等待timeout秒。\n",
    "- is_alive(self)：返回线程是否在运行。如果线程已经启动且尚未终止，则返回True，否则返回False。\n",
    "- getName(self)：返回线程的名称。\n",
    "- setName(self, name)：设置线程的名称。\n",
    "- ident属性：线程的唯一标识符。\n",
    "- daemon属性：线程的守护标志，用于指示是否是守护线程。\n",
    "- isDaemon()方法："
   ]
  },
  {
   "cell_type": "raw",
   "id": "48c4116e-d2b3-460e-b5a5-d105a5d9c434",
   "metadata": {},
   "source": [
    "import threading\n",
    "import time\n",
    "\n",
    "exitFlag = 0\n",
    "\n",
    "class myThread (threading.Thread):\n",
    "    def __init__(self, threadID, name, delay):\n",
    "        threading.Thread.__init__(self)\n",
    "        self.threadID = threadID\n",
    "        self.name = name\n",
    "        self.delay = delay\n",
    "    def run(self):\n",
    "        print (\"开始线程：\" + self.name)\n",
    "        print_time(self.name, self.delay, 5)\n",
    "        print (\"退出线程：\" + self.name)\n",
    "\n",
    "def print_time(threadName, delay, counter):\n",
    "    while counter:\n",
    "        if exitFlag:\n",
    "            threadName.exit()\n",
    "        time.sleep(delay)\n",
    "        print (\"%s: %s\" % (threadName, time.ctime(time.time())))\n",
    "        counter -= 1\n",
    "\n",
    "# 创建新线程\n",
    "thread1 = myThread(1, \"Thread-1\", 1)\n",
    "thread2 = myThread(2, \"Thread-2\", 2)\n",
    "\n",
    "# 开启新线程\n",
    "thread1.start()\n",
    "thread2.start()\n",
    "thread1.join()\n",
    "thread2.join()\n",
    "print (\"退出主线程\")"
   ]
  },
  {
   "cell_type": "raw",
   "id": "173ee913-e5ac-4a20-bcf7-0aa3208a2e0a",
   "metadata": {},
   "source": [
    "import queue\n",
    "import threading\n",
    "import time\n",
    "\n",
    "exitFlag = 0\n",
    "\n",
    "class myThread (threading.Thread):\n",
    "    def __init__(self, threadID, name, q):\n",
    "        threading.Thread.__init__(self)\n",
    "        self.threadID = threadID\n",
    "        self.name = name\n",
    "        self.q = q\n",
    "    def run(self):\n",
    "        print (\"开启线程：\" + self.name)\n",
    "        process_data(self.name, self.q)\n",
    "        print (\"退出线程：\" + self.name)\n",
    "\n",
    "def process_data(threadName, q):\n",
    "    while not exitFlag:\n",
    "        queueLock.acquire()\n",
    "        if not workQueue.empty():\n",
    "            data = q.get()\n",
    "            queueLock.release()\n",
    "            print (\"%s processing %s\" % (threadName, data))\n",
    "        else:\n",
    "            queueLock.release()\n",
    "        time.sleep(1)\n",
    "\n",
    "threadList = [\"Thread-1\", \"Thread-2\", \"Thread-3\"]\n",
    "nameList = [\"One\", \"Two\", \"Three\", \"Four\", \"Five\"]\n",
    "queueLock = threading.Lock()\n",
    "workQueue = queue.Queue(10)\n",
    "threads = []\n",
    "threadID = 1\n",
    "\n",
    "# 创建新线程\n",
    "for tName in threadList:\n",
    "    thread = myThread(threadID, tName, workQueue)\n",
    "    thread.start()\n",
    "    threads.append(thread)\n",
    "    threadID += 1\n",
    "\n",
    "# 填充队列\n",
    "queueLock.acquire()\n",
    "for word in nameList:\n",
    "    workQueue.put(word)\n",
    "queueLock.release()\n",
    "\n",
    "# 等待队列清空\n",
    "while not workQueue.empty():\n",
    "    pass\n",
    "\n",
    "# 通知线程是时候退出\n",
    "exitFlag = 1\n",
    "\n",
    "# 等待所有线程完成\n",
    "for t in threads:\n",
    "    t.join()\n",
    "print (\"退出主线程\")"
   ]
  },
  {
   "cell_type": "raw",
   "id": "d8788883-35b3-4eda-8efc-518bfb70a56d",
   "metadata": {},
   "source": [
    "import threading\n",
    "import time\n",
    "\n",
    "class myThread (threading.Thread):\n",
    "    def __init__(self, threadID, name, delay):\n",
    "        threading.Thread.__init__(self)\n",
    "        self.threadID = threadID\n",
    "        self.name = name\n",
    "        self.delay = delay\n",
    "    def run(self):\n",
    "        print (\"开启线程： \" + self.name)\n",
    "        # 获取锁，用于线程同步\n",
    "        threadLock.acquire()\n",
    "        print_time(self.name, self.delay, 3)\n",
    "        # 释放锁，开启下一个线程\n",
    "        threadLock.release()\n",
    "\n",
    "def print_time(threadName, delay, counter):\n",
    "    while counter:\n",
    "        time.sleep(delay)\n",
    "        print (\"%s: %s\" % (threadName, time.ctime(time.time())))\n",
    "        counter -= 1\n",
    "\n",
    "threadLock = threading.Lock()\n",
    "threads = []\n",
    "\n",
    "# 创建新线程\n",
    "thread1 = myThread(1, \"Thread-1\", 1)\n",
    "thread2 = myThread(2, \"Thread-2\", 2)\n",
    "\n",
    "# 开启新线程\n",
    "thread1.start()\n",
    "thread2.start()\n",
    "\n",
    "# 添加线程到线程列表\n",
    "threads.append(thread1)\n",
    "threads.append(thread2)\n",
    "\n",
    "# 等待所有线程完成\n",
    "for t in threads:\n",
    "    t.join()\n",
    "print (\"退出主线程\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6047aa9f-dd4b-4ff6-a767-2100501b07d3",
   "metadata": {},
   "outputs": [],
   "source": [
    "import xml.etree.ElementTree as ET\n",
    "\n",
    "# 定义一个 XML 字符串\n",
    "xml_string = '''\n",
    "<bookstore>\n",
    "    <book>\n",
    "        <title>Introduction to Python</title>\n",
    "        <author>John Doe</author>\n",
    "        <price>29.99</price>\n",
    "    </book>\n",
    "    <book>\n",
    "        <title>Data Science with Python</title>\n",
    "        <author>Jane Smith</author>\n",
    "        <price>39.95</price>\n",
    "    </book>\n",
    "</bookstore>\n",
    "'''\n",
    "\n",
    "# 使用 ElementTree 解析 XML 字符串\n",
    "root = ET.fromstring(xml_string)\n",
    "\n",
    "# 遍历 XML 树\n",
    "for book in root.findall('book'):\n",
    "    title = book.find('title').text\n",
    "    author = book.find('author').text\n",
    "    price = book.find('price').text\n",
    "    print(f'Title: {title}, Author: {author}, Price: {price}')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ed6c6617-e250-45fa-879c-c15806747998",
   "metadata": {},
   "source": [
    "# Python 编码为 JSON 类型转换对应表：\n",
    "\n",
    "|Python|JSON|\n",
    "|--|--|\n",
    "|dict|object|\n",
    "|list, tuple|array|\n",
    "|str|string|\n",
    "|int, float, int- & float-derived Enums|number|\n",
    "|True|true|\n",
    "|False|false|\n",
    "|None|null|"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ca04f924-1cd8-41e9-85eb-7a69c3d6ea27",
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "\n",
    "# Python 字典类型转换为 JSON 对象\n",
    "data1 = {\n",
    "    'no' : 1,\n",
    "    'name' : 'Runoob',\n",
    "    'url' : 'http://www.runoob.com'\n",
    "}\n",
    "\n",
    "# 写入 JSON 数据\n",
    "with open('data.json', 'w') as f:\n",
    "    json.dump(data1, f)\n",
    "\n",
    "# 读取数据\n",
    "with open('data.json', 'r') as f:\n",
    "    data = json.load(f)\n",
    "    print(data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7930bccd-19e1-4a3a-934b-35fd2b24f42a",
   "metadata": {},
   "outputs": [],
   "source": [
    "import time  # 引入time模块\n",
    "\n",
    "ticks = time.time()\n",
    "print (\"当前时间戳为:\", ticks)\n",
    "localtime = time.localtime(time.time())\n",
    "print (\"本地时间为 :\", localtime)\n",
    "localtime = time.asctime( time.localtime(time.time()) )\n",
    "print (\"本地时间为 :\", localtime)\n",
    "# 格式化成2016-03-20 11:45:39形式\n",
    "print (time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()))\n",
    "# 格式化成Sat Mar 28 22:24:24 2016形式\n",
    "print (time.strftime(\"%a %b %d %H:%M:%S %Y\", time.localtime()))\n",
    "# 将格式字符串转换为时间戳\n",
    "a = \"Sat Mar 28 22:24:24 2016\"\n",
    "print (time.mktime(time.strptime(a,\"%a %b %d %H:%M:%S %Y\")))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4782000e-0621-4c5f-85c4-11240d47eaf1",
   "metadata": {},
   "source": [
    "# python中时间日期格式化符号：\n",
    "\n",
    "- %y 两位数的年份表示（00-99）\n",
    "- %Y 四位数的年份表示（000-9999）\n",
    "- %m 月份（01-12）\n",
    "- %d 月内中的一天（0-31）\n",
    "- %H 24小时制小时数（0-23）\n",
    "- %I 12小时制小时数（01-12）\n",
    "- %M 分钟数（00=59）\n",
    "- %S 秒（00-59）\n",
    "- %a 本地简化星期名称\n",
    "- %A 本地完整星期名称\n",
    "- %b 本地简化的月份名称\n",
    "- %B 本地完整的月份名称\n",
    "- %c 本地相应的日期表示和时间表示\n",
    "- %j 年内的一天（001-366）\n",
    "- %p 本地A.M.或P.M.的等价符\n",
    "- %U 一年中的星期数（00-53）星期天为星期的开始\n",
    "- %w 星期（0-6），星期天为星期的开始\n",
    "- %W 一年中的星期数（00-53）星期一为星期的开始\n",
    "- %x 本地相应的日期表示\n",
    "- %X 本地相应的时间表示\n",
    "- %Z 当前时区的名称\n",
    "- %% %号本身"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "35869674-175c-4b27-8f3e-6545a85efef3",
   "metadata": {},
   "outputs": [],
   "source": [
    "import calendar\n",
    "\n",
    "cal = calendar.month(2016, 1)\n",
    "print (\"以下输出2016年1月份的日历:\")\n",
    "print (cal)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3516a945-4e77-4639-8c30-c6f244c2b60f",
   "metadata": {},
   "source": [
    "# Time 模块\n",
    "\n",
    "Time 模块包含了以下内置函数，既有时间处理的，也有转换时间格式的：\n",
    "\n",
    "|函数|描述|\n",
    "|--|--|\n",
    "|time.altzone|返回格林威治西部的夏令时地区的偏移秒数。如果该地区在格林威治东部会返回负值（如西欧，包括英国）。对夏令时启用地区才能使用。|\n",
    "|time.asctime([tupletime])|接受时间元组并返回一个可读的形式为\"Tue Dec 11 18:07:14 2008\"（2008年12月11日 周二18时07分14秒）的24个字符的字符串。|\n",
    "|time.clock()|用以浮点数计算的秒数返回当前的CPU时间。用来衡量不同程序的耗时，比time.time()更有用。|\n",
    "|time.ctime([secs])|作用相当于asctime(localtime(secs))，未给参数相当于asctime()|\n",
    "|time.gmtime([secs])|接收时间戳（1970纪元后经过的浮点秒数）并返回格林威治天文时间下的时间元组t。注：t.tm_isdst始终为0|\n",
    "|time.localtime([secs]|接收时间戳（1970纪元后经过的浮点秒数）并返回当地时间下的时间元组t（t.tm_isdst可取0或1，取决于当地当时是不是夏令时）。|\n",
    "|time.mktime(tupletime)|接受时间元组并返回时间戳（1970纪元后经过的浮点秒数）。|\n",
    "|time.sleep(secs)|推迟调用线程的运行，secs指秒数。|\n",
    "|time.strftime(fmt[,tupletime])|接收以时间元组，并返回以可读字符串表示的当地时间，格式由fmt决定。|\n",
    "|time.strptime(str,fmt='%a %b %d %H:%M:%S %Y')|根据fmt的格式把一个时间字符串解析为时间元组。|\n",
    "|time.time( )|返回当前时间的时间戳（1970纪元后经过的浮点秒数）。|\n",
    "|time.tzset()|根据环境变量TZ重新初始化时间相关设置。|\n",
    "|time.perf_counter()|返回计时器的精准时间（系统的运行时间），包含整个系统的睡眠时间。由于返回值的基准点是未定义的，所以，只有连续调用的结果之间的差才是有效的。|\n",
    "|time.process_time()|返回当前进程执行 CPU 的时间总和，不包含睡眠时间。由于返回值的基准点是未定义的，所以，只有连续调用的结果之间的差才是有效的。|\n",
    "\n",
    "|属性|描述|\n",
    "|--|--|\n",
    "|time.timezone|属性time.timezone是当地时区（未启动夏令时）距离格林威治的偏移秒数（>0，美洲;<=0大部分欧洲，亚洲，非洲）。|\n",
    "|time.tzname|属性time.tzname包含一对根据情况的不同而不同的字符串，分别是带夏令时的本地时区名称，和不带的。|"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c0c78d83-299d-4633-83ea-6ebec1d2fa7d",
   "metadata": {},
   "source": [
    "# 日历（Calendar）模块\n",
    "\n",
    "|函数|描述|\n",
    "|--|--|\n",
    "|calendar.calendar(year,w=2,l=1,c=6)|返回一个多行字符串格式的 year 年年历，3 个月一行，间隔距离为 c。 每日宽度间隔为w字符。每行长度为 21* W+18+2* C。l 是每星期行数。|\n",
    "|calendar.firstweekday( )|返回当前每周起始日期的设置。默认情况下，首次载入 calendar 模块时返回 0，即星期一。|\n",
    "|calendar.isleap(year)|是闰年返回 True，否则为 False。|\n",
    "|calendar.leapdays(y1,y2)|返回在Y1，Y2两年之间的闰年总数。|\n",
    "|calendar.month(year,month,w=2,l=1)|返回一个多行字符串格式的year年month月日历，两行标题，一周一行。每日宽度间隔为w字符。每行的长度为7* w+6。l是每星期的行数。|\n",
    "|calendar.monthcalendar(year,month)|返回一个整数的单层嵌套列表。每个子列表装载代表一个星期的整数。Year年month月外的日期都设为0;范围内的日子都由该月第几日表示，从1开始。|\n",
    "|calendar.monthrange(year,month)|返回两个整数。第一个是该月的星期几，第二个是该月有几天。星期几是从0（星期一）到 6（星期日）。|\n",
    "|calendar.prcal(year, w=0, l=0, c=6, m=3)|相当于 print (calendar.calendar(year, w=0, l=0, c=6, m=3))。|\n",
    "|calendar.prmonth(theyear, themonth, w=0, l=0)|相当于 print(calendar.month(theyear, themonth, w=0, l=0))。|\n",
    "|calendar.setfirstweekday(weekday)|设置每周的起始日期码。0（星期一）到6（星期日）。|\n",
    "|calendar.timegm(tupletime)|和time.gmtime相反：接受一个时间元组形式，返回该时刻的时间戳（1970纪元后经过的浮点秒数）。|\n",
    "|calendar.weekday(year,month,day)|返回给定日期的日期码。0（星期一）到6（星期日）。月份为 1（一月） 到 12（12月）。|"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "511ddb03-78f9-431b-9239-59e464ea3ac1",
   "metadata": {},
   "source": [
    "# Python3 内置函数\n",
    "\n",
    "||||||\n",
    "|--|--|--|--|--|\n",
    "|abs()|dict()|help()|min()|setattr()|\n",
    "|all()|dir()|hex()|next()|slice()|\n",
    "|any()|divmod()|id()|object()|sorted()|\n",
    "|ascii()|enumerate()|input()|oct()|staticmethod()|\n",
    "|bin()|eval()|int()|open()|str()|\n",
    "|bool()|exec()|isinstance()|ord()|sum()|\n",
    "|bytearray()|filter()|issubclass()|pow()|super()|\n",
    "|bytes()|float()|iter()|print()|tuple()|\n",
    "|callable()|format()|len()|property()|type()|\n",
    "|chr()|frozenset()|list()|range()|vars()|\n",
    "|classmethod()|getattr()|locals()|repr()|zip()|\n",
    "|compile()|globals()|map()|reversed()|__import__()|\n",
    "|complex()|hasattr()|max()|round()|reload()|\n",
    "|delattr()|hash()|memoryview()|set()||"
   ]
  },
  {
   "cell_type": "raw",
   "id": "e97ce5dd-443f-4500-9cb8-4dfcf9f9e302",
   "metadata": {},
   "source": [
    "from urllib.request import urlopen\n",
    "\n",
    "myURL = urlopen(\"https://www.runoob.com/\")\n",
    "print(myURL.read(300))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a5cd938e-020c-469e-a938-319b6dbd9d28",
   "metadata": {},
   "source": [
    "# operator 模块\n",
    "\n",
    "|运算|语法|函数|\n",
    "|--|--|--|\n",
    "|加法|a + b|add(a, b)|\n",
    "|字符串拼接|seq1 + seq2|concat(seq1, seq2)|\n",
    "|包含测试|obj in seq|contains(seq, obj)|\n",
    "|除法|a / b|truediv(a, b)|\n",
    "|除法|a // b|floordiv(a, b)|\n",
    "|按位与|a & b|and_(a, b)|\n",
    "|按位异或|a ^ b|xor(a, b)|\n",
    "|按位取反|~ a|invert(a)|\n",
    "|按位或|a | b|or_(a, b)|\n",
    "|取幂|a ** b|pow(a, b)|\n",
    "|标识|a is b|is_(a, b)|\n",
    "|标识|a is not b|is_not(a, b)|\n",
    "|索引赋值|obj[k] = v|setitem(obj, k, v)|\n",
    "|索引删除|del obj[k]|delitem(obj, k)|\n",
    "|索引取值|obj[k]|getitem(obj, k)|\n",
    "|左移|a << b|lshift(a, b)|\n",
    "|取模|a % b|mod(a, b)|\n",
    "|乘法|a * b|mul(a, b)|\n",
    "|矩阵乘法|a @ b|matmul(a, b)|\n",
    "|取反（算术）|- a|neg(a)\n",
    "|取反（逻辑）|not a|not_(a)\n",
    "|正数|+ a|pos(a)|\n",
    "|右移|a >> b|rshift(a, b)|\n",
    "|切片赋值|seq[i:j] = values|setitem(seq, slice(i, j), values)|\n",
    "|切片删除|del seq[i:j]|delitem(seq, slice(i, j))|\n",
    "|切片取值|seq[i:j]|getitem(seq, slice(i, j))|\n",
    "|字符串格式化|s % obj|mod(s, obj)|\n",
    "|减法|a - b|sub(a, b)|\n",
    "|真值测试|obj|truth(obj)|\n",
    "|比较|a < b|lt(a, b)|\n",
    "|比较|a <= b|le(a, b)|\n",
    "|相等|a == b|eq(a, b)|\n",
    "|不等|a != b|ne(a, b)|\n",
    "|比较|a >= b|ge(a, b)|\n",
    "|比较|a > b|gt(a, b)|"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "id": "e2da04c9-36a1-48d1-afd8-d1538e827b7c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['__doc__',\n",
       " '__loader__',\n",
       " '__name__',\n",
       " '__package__',\n",
       " '__spec__',\n",
       " 'acos',\n",
       " 'acosh',\n",
       " 'asin',\n",
       " 'asinh',\n",
       " 'atan',\n",
       " 'atan2',\n",
       " 'atanh',\n",
       " 'cbrt',\n",
       " 'ceil',\n",
       " 'comb',\n",
       " 'copysign',\n",
       " 'cos',\n",
       " 'cosh',\n",
       " 'degrees',\n",
       " 'dist',\n",
       " 'e',\n",
       " 'erf',\n",
       " 'erfc',\n",
       " 'exp',\n",
       " 'exp2',\n",
       " 'expm1',\n",
       " 'fabs',\n",
       " 'factorial',\n",
       " 'floor',\n",
       " 'fmod',\n",
       " 'frexp',\n",
       " 'fsum',\n",
       " 'gamma',\n",
       " 'gcd',\n",
       " 'hypot',\n",
       " 'inf',\n",
       " 'isclose',\n",
       " 'isfinite',\n",
       " 'isinf',\n",
       " 'isnan',\n",
       " 'isqrt',\n",
       " 'lcm',\n",
       " 'ldexp',\n",
       " 'lgamma',\n",
       " 'log',\n",
       " 'log10',\n",
       " 'log1p',\n",
       " 'log2',\n",
       " 'modf',\n",
       " 'nan',\n",
       " 'nextafter',\n",
       " 'perm',\n",
       " 'pi',\n",
       " 'pow',\n",
       " 'prod',\n",
       " 'radians',\n",
       " 'remainder',\n",
       " 'sin',\n",
       " 'sinh',\n",
       " 'sqrt',\n",
       " 'sumprod',\n",
       " 'tan',\n",
       " 'tanh',\n",
       " 'tau',\n",
       " 'trunc',\n",
       " 'ulp']"
      ]
     },
     "execution_count": 46,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import math\n",
    "dir(math)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4c3ac112-afc2-4f90-a548-551af1adf05c",
   "metadata": {},
   "source": [
    "# math 模块常量\n",
    "\n",
    "|常量|描述|\n",
    "|--|--|\n",
    "|math.e|返回欧拉数 (2.7182...)|\n",
    "|math.inf|返回正无穷大浮点数|\n",
    "|math.nan|返回一个浮点值 NaN (not a number)|\n",
    "|math.pi|π 一般指圆周率。 圆周率 PI (3.1415...)|\n",
    "|math.tau|数学常数 τ = 6.283185...，精确到可用精度。Tau 是一个圆周常数，等于 2π，圆的周长与半径之比。|"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7616f28e-759a-4088-b00a-8b86b787422f",
   "metadata": {},
   "source": [
    "#  math 模块方法\n",
    "\n",
    "|方法|描述|\n",
    "|--|--|\n",
    "|math.acos(x)|返回 x 的反余弦，结果范围在 0 到 pi 之间。|\n",
    "|math.acosh(x)|返回 x 的反双曲余弦值。|\n",
    "|math.asin(x)|返回 x 的反正弦值，结果范围在 -pi/2 到 pi/2 之间。|\n",
    "|math.asinh(x)|返回 x 的反双曲正弦值。|\n",
    "|math.atan(x)|返回 x 的反正切值，结果范围在 -pi/2 到 pi/2 之间。|\n",
    "|math.atan2(y, x)|返回给定的 X 及 Y 坐标值的反正切值，结果是在 -pi 和 pi 之间。|\n",
    "|math.atanh(x)|返回 x 的反双曲正切值。|\n",
    "|math.ceil(x)|将 x 向上舍入到最接近的整数|\n",
    "|math.comb(n, k)|返回不重复且无顺序地从 n 项中选择 k 项的方式总数。|\n",
    "|math.copysign(x, y)|返回一个基于 x 的绝对值和 y 的符号的浮点数。|\n",
    "|math.cos()|返回 x 弧度的余弦值。|\n",
    "|math.cosh(x)|返回 x 的双曲余弦值。|\n",
    "|math.degrees(x)|将角度 x 从弧度转换为度数。|\n",
    "|math.dist(p, q)|返回 p 与 q 两点之间的欧几里得距离，以一个坐标序列（或可迭代对象）的形式给出。 两个点必须具有相同的维度。|\n",
    "|math.erf(x)|返回一个数的误差函数|\n",
    "|math.erfc(x)|返回 x 处的互补误差函数|\n",
    "|math.exp(x)|返回 e 的 x 次幂，Ex， 其中 e = 2.718281... 是自然对数的基数。|\n",
    "|math.expm1()|返回 Ex - 1， e 的 x 次幂，Ex，其中 e = 2.718281... 是自然对数的基数。这通常比 math.e ** x 或 pow(math.e, x) 更精确。|\n",
    "|math.fabs(x)|返回 x 的绝对值。|\n",
    "|math.factorial(x)|返回 x 的阶乘。 如果 x 不是整数或为负数时则将引发 ValueError。|\n",
    "|math.floor()|将数字向下舍入到最接近的整数|\n",
    "|math.fmod(x, y)|返回 x/y 的余数|\n",
    "|math.frexp(x)|以 (m, e) 对的形式返回 x 的尾数和指数。 m 是一个浮点数， e 是一个整数，正好是 x == m * 2**e 。 如果 x 为零，则返回 (0.0, 0) ，否则返回 0.5 <= abs(m) < 1 。|\n",
    "|math.fsum(iterable)|返回可迭代对象 (元组, 数组, 列表, 等)中的元素总和，是浮点值。|\n",
    "|math.gamma(x)|返回 x 处的伽马函数值。|\n",
    "|math.gcd()|返回给定的整数参数的最大公约数。|\n",
    "|math.hypot()|返回欧几里得范数，sqrt(sum(x**2 for x in coordinates))。 这是从原点到坐标给定点的向量长度。|\n",
    "|math.isclose(a,b)|检查两个值是否彼此接近，若 a 和 b 的值比较接近则返回 True，否则返回 False。|\n",
    "|math.isfinite(x)|判断 x 是否有限，如果 x 既不是无穷大也不是 NaN，则返回 True ，否则返回 False 。|\n",
    "|math.isinf(x)|判断 x 是否是无穷大，如果 x 是正或负无穷大，则返回 True ，否则返回 False 。|\n",
    "|math.isnan()|判断数字是否为 NaN，如果 x 是 NaN（不是数字），则返回 True ，否则返回 False 。|\n",
    "|math.isqrt()|将平方根数向下舍入到最接近的整数|\n",
    "|math.ldexp(x, i)|返回 x * (2**i) 。 这基本上是函数 math.frexp() 的反函数。|\n",
    "|math.lgamma()|返回伽玛函数在 x 绝对值的自然对数。|\n",
    "|math.log(x[, base])|使用一个参数，返回 x 的自然对数（底为 e ）。|\n",
    "|math.log10(x)|返回 x 底为 10 的对数。|\n",
    "|math.log1p(x)|返回 1+x 的自然对数（以 e 为底）。|\n",
    "|math.log2(x)|返回 x 以 2 为底的对数|\n",
    "|math.perm(n, k=None)|返回不重复且有顺序地从 n 项中选择 k 项的方式总数。|\n",
    "|math.pow(x, y)|将返回 x 的 y 次幂。|\n",
    "|math.prod(iterable)|计算可迭代对象中所有元素的积。|\n",
    "|math.radians(x)|将角度 x 从度数转换为弧度。|\n",
    "|math.remainder(x, y)|返回 IEEE 754 风格的 x 除于 y 的余数。|\n",
    "|math.sin(x)|返回 x 弧度的正弦值。|\n",
    "|math.sinh(x)|返回 x 的双曲正弦值。|\n",
    "|math.sqrt(x)|返回 x 的平方根。|\n",
    "|math.tan(x)|返回 x 弧度的正切值。|\n",
    "|math.tanh(x)|返回 x 的双曲正切值。|\n",
    "|math.trunc(x)|返回 x 截断整数的部分，即返回整数部分，删除小数部分|"
   ]
  },
  {
   "cell_type": "raw",
   "id": "c60fc3fa-b183-47db-a868-33bc2b8dbf0b",
   "metadata": {},
   "source": [
    "# requests 模块\n",
    "\n",
    "# 导入 requests 包\n",
    "import requests\n",
    "\n",
    "# 发送请求\n",
    "x = requests.get('https://www.runoob.com/')\n",
    "\n",
    "# 返回网页内容\n",
    "print(x.text)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "78f082e5-b636-41d3-a494-acd8cdcb1056",
   "metadata": {},
   "source": [
    "|属性或方法|说明|\n",
    "|--|--|\n",
    "|apparent_encoding|编码方式|\n",
    "|close()|关闭与服务器的连接|\n",
    "|content|返回响应的内容，以字节为单位|\n",
    "|cookies|返回一个 CookieJar 对象，包含了从服务器发回的 cookie|\n",
    "|elapsed|返回一个 timedelta 对象，包含了从发送请求到响应到达之间经过的时间量，可以用于测试响应速度。比如 r.elapsed.microseconds 表示响应到达需要多少微秒。|\n",
    "|encoding|解码 r.text 的编码方式|\n",
    "|headers|返回响应头，字典格式|\n",
    "|history|返回包含请求历史的响应对象列表（url）|\n",
    "|is_permanent_redirect|如果响应是永久重定向的 url，则返回 True，否则返回 False|\n",
    "|is_redirect|如果响应被重定向，则返回 True，否则返回 False|\n",
    "|iter_content()|迭代响应|\n",
    "|iter_lines()|迭代响应的行|\n",
    "|json()|返回结果的 JSON 对象 (结果需要以 JSON 格式编写的，否则会引发错误)|\n",
    "|links|返回响应的解析头链接|\n",
    "|next|返回重定向链中下一个请求的 PreparedRequest 对象|\n",
    "|ok|检查 \"status_code\" 的值，如果小于400，则返回 True，如果不小于 400，则返回 False|\n",
    "|raise_for_status()|如果发生错误，方法返回一个 HTTPError 对象|\n",
    "|reason|响应状态的描述，比如 \"Not Found\" 或 \"OK\"|\n",
    "|request|返回请求此响应的请求对象|\n",
    "|status_code|返回 http 的状态码，比如 404 和 200（200 是 OK，404 是 Not Found）|\n",
    "|text|返回响应的内容，unicode 类型数据|\n",
    "|url|返回响应的 URL|"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "358b8b3c-4e8e-44e5-a927-23cfcbfccf87",
   "metadata": {},
   "source": [
    "# requests 方法\n",
    "\n",
    "|方法|描述|\n",
    "|--|--|\n",
    "|delete(url, args)|发送 DELETE 请求到指定 url|\n",
    "|get(url, params, args)|发送 GET 请求到指定 url|\n",
    "|head(url, args)|发送 HEAD 请求到指定 url|\n",
    "|patch(url, data, args)|发送 PATCH 请求到指定 url|\n",
    "|post(url, data, json, args)|发送 POST 请求到指定 url|\n",
    "|put(url, data, args)|发送 PUT 请求到指定 url|\n",
    "|request(method, url, args)|向指定的 url 发送指定的请求方法|"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "id": "672d5c8c-ca94-4d2b-aef5-65ecbae47be4",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['BPF',\n",
       " 'LOG4',\n",
       " 'NV_MAGICCONST',\n",
       " 'RECIP_BPF',\n",
       " 'Random',\n",
       " 'SG_MAGICCONST',\n",
       " 'SystemRandom',\n",
       " 'TWOPI',\n",
       " '_ONE',\n",
       " '_Sequence',\n",
       " '__all__',\n",
       " '__builtins__',\n",
       " '__cached__',\n",
       " '__doc__',\n",
       " '__file__',\n",
       " '__loader__',\n",
       " '__name__',\n",
       " '__package__',\n",
       " '__spec__',\n",
       " '_accumulate',\n",
       " '_acos',\n",
       " '_bisect',\n",
       " '_ceil',\n",
       " '_cos',\n",
       " '_e',\n",
       " '_exp',\n",
       " '_fabs',\n",
       " '_floor',\n",
       " '_index',\n",
       " '_inst',\n",
       " '_isfinite',\n",
       " '_lgamma',\n",
       " '_log',\n",
       " '_log2',\n",
       " '_os',\n",
       " '_pi',\n",
       " '_random',\n",
       " '_repeat',\n",
       " '_sha512',\n",
       " '_sin',\n",
       " '_sqrt',\n",
       " '_test',\n",
       " '_test_generator',\n",
       " '_urandom',\n",
       " '_warn',\n",
       " 'betavariate',\n",
       " 'binomialvariate',\n",
       " 'choice',\n",
       " 'choices',\n",
       " 'expovariate',\n",
       " 'gammavariate',\n",
       " 'gauss',\n",
       " 'getrandbits',\n",
       " 'getstate',\n",
       " 'lognormvariate',\n",
       " 'normalvariate',\n",
       " 'paretovariate',\n",
       " 'randbytes',\n",
       " 'randint',\n",
       " 'random',\n",
       " 'randrange',\n",
       " 'sample',\n",
       " 'seed',\n",
       " 'setstate',\n",
       " 'shuffle',\n",
       " 'triangular',\n",
       " 'uniform',\n",
       " 'vonmisesvariate',\n",
       " 'weibullvariate']"
      ]
     },
     "execution_count": 48,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import random\n",
    "dir(random)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "id": "a8139689-d073-4807-b5b1-a0cb91141b0d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "使用默认种子生成随机数： 0.023716692139899576\n",
      "使用默认种子生成随机数： 0.6783967532297442\n",
      "使用整数 10 种子生成随机数： 0.5714025946899135\n",
      "使用整数 10 种子生成随机数： 0.5714025946899135\n",
      "使用字符串种子生成随机数： 0.3537754404730722\n"
     ]
    }
   ],
   "source": [
    "import random\n",
    "\n",
    "random.seed()\n",
    "print (\"使用默认种子生成随机数：\", random.random())\n",
    "print (\"使用默认种子生成随机数：\", random.random())\n",
    "\n",
    "random.seed(10)\n",
    "print (\"使用整数 10 种子生成随机数：\", random.random())\n",
    "random.seed(10)\n",
    "print (\"使用整数 10 种子生成随机数：\", random.random())\n",
    "\n",
    "random.seed(\"hello\",2)\n",
    "print (\"使用字符串种子生成随机数：\", random.random())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ac3da37f-bc87-4b36-9c22-8dcb4f9c6956",
   "metadata": {},
   "source": [
    "|方法|描述|\n",
    "|--|--|\n",
    "|seed()|初始化随机数生成器|\n",
    "|getstate()|返回捕获生成器当前内部状态的对象。|\n",
    "|setstate()|state 应该是从之前调用 getstate() 获得的，并且 setstate() 将生成器的内部状态恢复到 getstate() 被调用时的状态。|\n",
    "|getrandbits(k)|返回具有 k 个随机比特位的非负 Python 整数。 此方法随 MersenneTwister 生成器一起提供，其他一些生成器也可能将其作为 API 的可选部分提供。 在可能的情况下，getrandbits() 会启用 randrange() 来处理任意大的区间。|\n",
    "|randrange()|从 range(start, stop, step) 返回一个随机选择的元素。|\n",
    "|randint(a, b)|返回随机整数 N 满足 a <= N <= b。|\n",
    "|choice(seq)|从非空序列 seq 返回一个随机元素。 如果 seq 为空，则引发 IndexError。|\n",
    "|choices(population, weights=None, *, cum_weights=None, k=1)|从 population 中选择替换，返回大小为 k 的元素列表。 如果 population 为空，则引发 IndexError。|\n",
    "|shuffle(x[, random])|将序列 x 随机打乱位置。|\n",
    "|sample(population, k, *, counts=None)|返回从总体序列或集合中选择的唯一元素的 k 长度列表。 用于无重复的随机抽样。|\n",
    "|random()|返回 [0.0, 1.0) 范围内的下一个随机浮点数。|\n",
    "|uniform()|返回一个随机浮点数 N ，当 a <= b 时 a <= N <= b ，当 b < a 时 b <= N <= a 。|\n",
    "|triangular(low, high, mode)|返回一个随机浮点数 N ，使得 low <= N <= high 并在这些边界之间使用指定的 mode 。 low 和 high 边界默认为零和一。 mode 参数默认为边界之间的中点，给出对称分布。|\n",
    "|betavariate(alpha, beta)|Beta 分布。 参数的条件是 alpha > 0 和 beta > 0。 返回值的范围介于 0 和 1 之间。|\n",
    "|expovariate(lambd)|指数分布。 lambd 是 1.0 除以所需的平均值，它应该是非零的。|\n",
    "|gammavariate()|Gamma 分布（ 不是伽马函数） 参数的条件是 alpha > 0 和 beta > 0。|\n",
    "|gauss(mu, sigma)|正态分布，也称高斯分布。 mu 为平均值，而 sigma 为标准差。 此函数要稍快于下面所定义的 normalvariate() 函数。|\n",
    "|lognormvariate(mu, sigma)|对数正态分布。 如果你采用这个分布的自然对数，你将得到一个正态分布，平均值为 mu 和标准差为 sigma 。 mu 可以是任何值，sigma 必须大于零。|\n",
    "|normalvariate(mu, sigma)|正态分布。 mu 是平均值，sigma 是标准差。|\n",
    "|vonmisesvariate(mu, kappa)|冯·米塞斯分布。 mu 是平均角度，以弧度表示，介于0和 2*pi 之间，kappa 是浓度参数，必须大于或等于零。 如果 kappa 等于零，则该分布在 0 到 2*pi 的范围内减小到均匀的随机角度。|\n",
    "|paretovariate(alpha)|帕累托分布。 alpha 是形状参数。|\n",
    "|weibullvariate(alpha, beta)|威布尔分布。 alpha 是比例参数，beta 是形状参数。|"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ae3253af-6c01-4e6b-bb63-fe41fc963abc",
   "metadata": {},
   "source": [
    "# statistics 模块\n",
    "\n",
    "|方法|描述|\n",
    "|--|--|\n",
    "|statistics.harmonic_mean()|计算给定数据集的调和平均值。|\n",
    "|statistics.mean()|计算数据集的平均值|\n",
    "|statistics.median()|计算数据集的中位数|\n",
    "|statistics.median_grouped()|计算给定分组数据集的分组中位数|\n",
    "|statistics.median_high()|计算给定数据集的高位中位数|\n",
    "|statistics.median_low()|计算给定数据集的低位中位数。|\n",
    "|statistics.mode()|算数据集的众数（出现频率最高的值）|\n",
    "|statistics.pstdev()|计算给定数据集的样本标准偏差|\n",
    "|statistics.stdev()|计算数据集的标准差|\n",
    "|statistics.pvariance()|计算给定数据集的样本方差|\n",
    "|statistics.variance()|计算数据集的方差|\n",
    "|statistics.quantiles()|计算数据集的分位数，可指定分位数的数量（默认为四分位数）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "id": "ae7543e1-f912-42bb-a23d-cb9b3182dd65",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['Counter',\n",
       " 'Decimal',\n",
       " 'Fraction',\n",
       " 'LinearRegression',\n",
       " 'NormalDist',\n",
       " 'StatisticsError',\n",
       " '_SQRT2',\n",
       " '__all__',\n",
       " '__annotations__',\n",
       " '__builtins__',\n",
       " '__cached__',\n",
       " '__doc__',\n",
       " '__file__',\n",
       " '__loader__',\n",
       " '__name__',\n",
       " '__package__',\n",
       " '__spec__',\n",
       " '_coerce',\n",
       " '_convert',\n",
       " '_decimal_sqrt_of_frac',\n",
       " '_exact_ratio',\n",
       " '_fail_neg',\n",
       " '_float_sqrt_of_frac',\n",
       " '_integer_sqrt_of_frac_rto',\n",
       " '_isfinite',\n",
       " '_mean_stdev',\n",
       " '_normal_dist_inv_cdf',\n",
       " '_rank',\n",
       " '_sqrt_bit_width',\n",
       " '_ss',\n",
       " '_sum',\n",
       " 'bisect_left',\n",
       " 'bisect_right',\n",
       " 'correlation',\n",
       " 'count',\n",
       " 'covariance',\n",
       " 'defaultdict',\n",
       " 'erf',\n",
       " 'exp',\n",
       " 'fabs',\n",
       " 'fmean',\n",
       " 'fsum',\n",
       " 'geometric_mean',\n",
       " 'groupby',\n",
       " 'harmonic_mean',\n",
       " 'hypot',\n",
       " 'itemgetter',\n",
       " 'linear_regression',\n",
       " 'log',\n",
       " 'math',\n",
       " 'mean',\n",
       " 'median',\n",
       " 'median_grouped',\n",
       " 'median_high',\n",
       " 'median_low',\n",
       " 'mode',\n",
       " 'multimode',\n",
       " 'namedtuple',\n",
       " 'numbers',\n",
       " 'pstdev',\n",
       " 'pvariance',\n",
       " 'quantiles',\n",
       " 'random',\n",
       " 'reduce',\n",
       " 'repeat',\n",
       " 'sqrt',\n",
       " 'stdev',\n",
       " 'sumprod',\n",
       " 'sys',\n",
       " 'tau',\n",
       " 'variance']"
      ]
     },
     "execution_count": 50,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import statistics\n",
    "dir(statistics)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a1bca5aa-6efa-441a-8aaf-54573d5fc166",
   "metadata": {},
   "source": [
    "# hashlib 模块\n",
    "\n",
    "|算法名称|摘要长度（位）|输出长度（字节）|安全性|用途|\n",
    "|--|--|--|--|--|\n",
    "|md5|128|16|不安全|数据完整性验证、密码存储等|\n",
    "|sha1|160|20|不安全|数据完整性验证、密码存储等|\n",
    "|sha224|224|28|低|数据完整性验证、数字签名等|\n",
    "|sha256|256|32|中等|数据完整性验证、数字签名等|\n",
    "|sha384|384|48|高|数字签名、加密算法等|\n",
    "|sha512|512|64|高|数字签名、加密算法等|\n",
    "|sha3_224|224|28|高|未来标准的 SHA-3 家族成员，适用于数字签名等|\n",
    "|sha3_256|256|32|高|未来标准的 SHA-3 家族成员，适用于数字签名等|\n",
    "|sha3_384|384|48|高|未来标准的 SHA-3 家族成员，适用于数字签名等|\n",
    "|sha3_512|512|64|高|未来标准的 SHA-3 家族成员，适用于数字签名等|\n",
    "|shake_128|可变|可变|高|SHAKE 系列是 SHA-3 家族的可变长度版本，适用于各种应用|\n",
    "|shake_256|可变|可变|高|SHAKE 系列是 SHA-3 家族的可变长度版本，适用于各种应用|"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "id": "cba1c08b-5c36-405c-91da-7ba1cbdf6440",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['__all__',\n",
       " '__block_openssl_constructor',\n",
       " '__builtin_constructor_cache',\n",
       " '__builtins__',\n",
       " '__cached__',\n",
       " '__doc__',\n",
       " '__file__',\n",
       " '__get_builtin_constructor',\n",
       " '__loader__',\n",
       " '__name__',\n",
       " '__package__',\n",
       " '__spec__',\n",
       " '_hashlib',\n",
       " 'algorithms_available',\n",
       " 'algorithms_guaranteed',\n",
       " 'blake2b',\n",
       " 'blake2s',\n",
       " 'file_digest',\n",
       " 'md5',\n",
       " 'new',\n",
       " 'pbkdf2_hmac',\n",
       " 'scrypt',\n",
       " 'sha1',\n",
       " 'sha224',\n",
       " 'sha256',\n",
       " 'sha384',\n",
       " 'sha3_224',\n",
       " 'sha3_256',\n",
       " 'sha3_384',\n",
       " 'sha3_512',\n",
       " 'sha512',\n",
       " 'shake_128',\n",
       " 'shake_256']"
      ]
     },
     "execution_count": 51,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import hashlib\n",
    "dir(hashlib)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "id": "661ec8a5-9581-45fb-8e3f-1df0f55d29ef",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "7cfe50493eebd48ee7330c797459c2d0d5ca943bd1c84ad7a0b6783b11cd49d06b4a1dc84ee9ea5e20d0bfedbdb67e716500a20e5870abecea3f32dc8484a811\n"
     ]
    }
   ],
   "source": [
    "import hashlib\n",
    "\n",
    "sha512_hash = hashlib.sha512(b'RUNOOB')\n",
    "print(sha512_hash.hexdigest())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7a24c2b7-7ff9-4804-9d4e-db7d4b4ee0d2",
   "metadata": {},
   "source": [
    "# sys 模块\n",
    "\n",
    "## sys 模块常用属性\n",
    "\n",
    "|属性|说明|\n",
    "|--|--|\n",
    "|sys.argv|命令行参数列表，sys.argv[0] 是脚本名称|\n",
    "|sys.path|Python 模块搜索路径（PYTHONPATH）|\n",
    "|sys.modules|已加载模块的字典|\n",
    "|sys.platform|操作系统平台标识（如 'win32', 'linux', 'darwin'）|\n",
    "|sys.version|Python 解释器版本信息|\n",
    "|sys.executable|Python 解释器的绝对路径|\n",
    "|sys.stdin|标准输入流（文件对象）|\n",
    "|sys.stdout|标准输出流（文件对象）|\n",
    "|sys.stderr|标准错误流（文件对象）|\n",
    "|sys.byteorder|字节序（'little' 或 'big'）|\n",
    "|sys.maxsize|最大整数值（2**31-1 或 2**63-1）|\n",
    "\n",
    "## sys 模块常用方法\n",
    "\n",
    "|方法|说明|\n",
    "|--|--|\n",
    "|sys.exit([status])|退出程序，status=0 表示正常退出|\n",
    "|sys.getsizeof(obj)|返回对象占用的内存字节数|\n",
    "|sys.getdefaultencoding()|获取默认字符串编码（通常 'utf-8'）|\n",
    "|sys.setrecursionlimit(limit)|设置递归深度限制（默认 1000）|\n",
    "|sys.getrecursionlimit()|获取当前递归深度限制|\n",
    "|sys.getrefcount(obj)|返回对象的引用计数|\n",
    "|sys.exc_info()|获取当前异常信息（(type, value, traceback)）|\n",
    "|sys.settrace(tracefunc)|设置调试跟踪函数|\n",
    "|sys.setprofile(profilefunc)|设置性能分析函数|"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "id": "8c50765e-95d1-4578-98a7-bedf4449d37c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['__breakpointhook__',\n",
       " '__displayhook__',\n",
       " '__doc__',\n",
       " '__excepthook__',\n",
       " '__interactivehook__',\n",
       " '__loader__',\n",
       " '__name__',\n",
       " '__package__',\n",
       " '__spec__',\n",
       " '__stderr__',\n",
       " '__stdin__',\n",
       " '__stdout__',\n",
       " '__unraisablehook__',\n",
       " '_base_executable',\n",
       " '_clear_type_cache',\n",
       " '_current_exceptions',\n",
       " '_current_frames',\n",
       " '_debugmallocstats',\n",
       " '_framework',\n",
       " '_getframe',\n",
       " '_getframemodulename',\n",
       " '_git',\n",
       " '_home',\n",
       " '_setprofileallthreads',\n",
       " '_settraceallthreads',\n",
       " '_stdlib_dir',\n",
       " '_xoptions',\n",
       " 'abiflags',\n",
       " 'activate_stack_trampoline',\n",
       " 'addaudithook',\n",
       " 'api_version',\n",
       " 'argv',\n",
       " 'audit',\n",
       " 'base_exec_prefix',\n",
       " 'base_prefix',\n",
       " 'breakpointhook',\n",
       " 'builtin_module_names',\n",
       " 'byteorder',\n",
       " 'call_tracing',\n",
       " 'copyright',\n",
       " 'deactivate_stack_trampoline',\n",
       " 'displayhook',\n",
       " 'dont_write_bytecode',\n",
       " 'exc_info',\n",
       " 'excepthook',\n",
       " 'exception',\n",
       " 'exec_prefix',\n",
       " 'executable',\n",
       " 'exit',\n",
       " 'flags',\n",
       " 'float_info',\n",
       " 'float_repr_style',\n",
       " 'get_asyncgen_hooks',\n",
       " 'get_coroutine_origin_tracking_depth',\n",
       " 'get_int_max_str_digits',\n",
       " 'getallocatedblocks',\n",
       " 'getdefaultencoding',\n",
       " 'getdlopenflags',\n",
       " 'getfilesystemencodeerrors',\n",
       " 'getfilesystemencoding',\n",
       " 'getprofile',\n",
       " 'getrecursionlimit',\n",
       " 'getrefcount',\n",
       " 'getsizeof',\n",
       " 'getswitchinterval',\n",
       " 'gettrace',\n",
       " 'getunicodeinternedsize',\n",
       " 'hash_info',\n",
       " 'hexversion',\n",
       " 'implementation',\n",
       " 'int_info',\n",
       " 'intern',\n",
       " 'is_finalizing',\n",
       " 'is_stack_trampoline_active',\n",
       " 'last_exc',\n",
       " 'last_traceback',\n",
       " 'last_type',\n",
       " 'last_value',\n",
       " 'maxsize',\n",
       " 'maxunicode',\n",
       " 'meta_path',\n",
       " 'modules',\n",
       " 'monitoring',\n",
       " 'orig_argv',\n",
       " 'path',\n",
       " 'path_hooks',\n",
       " 'path_importer_cache',\n",
       " 'platform',\n",
       " 'platlibdir',\n",
       " 'prefix',\n",
       " 'ps1',\n",
       " 'ps2',\n",
       " 'ps3',\n",
       " 'pycache_prefix',\n",
       " 'set_asyncgen_hooks',\n",
       " 'set_coroutine_origin_tracking_depth',\n",
       " 'set_int_max_str_digits',\n",
       " 'setdlopenflags',\n",
       " 'setprofile',\n",
       " 'setrecursionlimit',\n",
       " 'setswitchinterval',\n",
       " 'settrace',\n",
       " 'stderr',\n",
       " 'stdin',\n",
       " 'stdlib_module_names',\n",
       " 'stdout',\n",
       " 'thread_info',\n",
       " 'unraisablehook',\n",
       " 'version',\n",
       " 'version_info',\n",
       " 'warnoptions']"
      ]
     },
     "execution_count": 54,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import sys\n",
    "dir(sys)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1666d624-1253-4978-a6b6-e8ebf3b42a4f",
   "metadata": {},
   "source": [
    "# Pickle 模块\n",
    "\n",
    "## pickle 模块常用方法\n",
    "\n",
    "|方法|说明|示例|\n",
    "|--|--|--|\n",
    "|pickle.dump(obj, file)|将对象序列化并写入文件|pickle.dump(data, open('data.pkl', 'wb'))|\n",
    "|pickle.load(file)|从文件读取并反序列化对象|data = pickle.load(open('data.pkl', 'rb'))|\n",
    "|pickle.dumps(obj)|将对象序列化为字节串|bytes_data = pickle.dumps([1, 2, 3])|\n",
    "|pickle.loads(bytes)|从字节串反序列化对象|lst = pickle.loads(bytes_data)|\n",
    "|pickle.HIGHEST_PROTOCOL|可用的最高协议版本（属性）|pickle.dump(..., protocol=pickle.HIGHEST_PROTOCOL)|\n",
    "|pickle.DEFAULT_PROTOCOL|默认协议版本（属性，通常为4）|pickle.dumps(obj, protocol=pickle.DEFAULT_PROTOCOL)|\n",
    "\n",
    "## pickle 模块协议版本|\n",
    "\n",
    "|协议版本|说明|\n",
    "|--|--|\n",
    "|0|人类可读的ASCII格式（兼容旧版）|\n",
    "|1|二进制格式（兼容旧版）|\n",
    "|2|Python 2.3+ 优化支持类对象|\n",
    "|3|Python 3.0+ 默认协议（不支持Python 2）|\n",
    "|4|Python 3.4+ 支持更大对象和更多数据类型|\n",
    "|5|Python 3.8+ 支持内存优化和数据共享|"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "id": "ef313542-d805-4b32-81f8-00c91c18d071",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Bob 30\n"
     ]
    }
   ],
   "source": [
    "import pickle\n",
    "\n",
    "class Person:\n",
    "    def __init__(self, name, age):\n",
    "        self.name = name\n",
    "        self.age = age\n",
    "\n",
    "    def __getstate__(self):\n",
    "        # 自定义序列化逻辑\n",
    "        return {'name': self.name, 'age': self.age}\n",
    "\n",
    "    def __setstate__(self, state):\n",
    "        # 自定义反序列化逻辑\n",
    "        self.name = state['name']\n",
    "        self.age = state['age']\n",
    "\n",
    "# 创建对象并序列化\n",
    "person = Person('Bob', 30)\n",
    "with open('person.pkl', 'wb') as file:\n",
    "    pickle.dump(person, file)\n",
    "\n",
    "# 反序列化对象\n",
    "with open('person.pkl', 'rb') as file:\n",
    "    loaded_person = pickle.load(file)\n",
    "\n",
    "print(loaded_person.name, loaded_person.age)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "id": "dd30f4ba-45cc-4581-a5f5-f2bdeb01c470",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'name': 'Alice', 'age': 25}\n"
     ]
    }
   ],
   "source": [
    "data = {'name': 'Alice', 'age': 25}\n",
    "with open('data.pkl', 'wb') as f:\n",
    "    pickle.dump(data, f, protocol=pickle.HIGHEST_PROTOCOL)\n",
    "with open('data.pkl', 'rb') as f:\n",
    "    loaded_data = pickle.load(f)\n",
    "print(loaded_data)  # 输出: {'name': 'Alice', 'age': 25}\n",
    "bytes_data = pickle.dumps([1, 2, 3], protocol=4)\n",
    "restored_list = pickle.loads(bytes_data)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c088a572-891a-47ff-bb8a-39389663c482",
   "metadata": {},
   "source": [
    "# subprocess 模块\n",
    "\n",
    "## subprocess 模块核心方法\n",
    "\n",
    "|方法|说明|示例|\n",
    "|--|--|--|\n",
    "|subprocess.run()|执行命令并等待完成（推荐）|subprocess.run([\"ls\", \"-l\"], capture_output=True, text=True)|\n",
    "|subprocess.Popen()|创建子进程（底层控制）|proc = subprocess.Popen([\"ping\", \"google.com\"], stdout=subprocess.PIPE)|\n",
    "|subprocess.call()|执行命令并返回退出码（旧版）|exit_code = subprocess.call([\"python\", \"--version\"])|\n",
    "|subprocess.check_call()|执行命令，失败时抛出异常|subprocess.check_call([\"git\", \"commit\"])|\n",
    "|subprocess.check_output()|执行命令并返回输出（旧版）|output = subprocess.check_output([\"date\"], text=True)|\n",
    "\n",
    "## subprocess.CompletedProcess 对象属性（run() 方法的返回对象）\n",
    "\n",
    "|属性|说明|\n",
    "|--|--|\n",
    "|args|执行的命令参数列表|\n",
    "|returncode|进程退出状态码（0表示成功）|\n",
    "|stdout|标准输出内容（若设置了capture_output）|\n",
    "|stderr|标准错误内容（若设置了capture_output）|\n",
    "\n",
    "## subprocess.Popen 类常用方法/属性\n",
    "\n",
    "|方法/属性|说明|示例|\n",
    "|--|--|--|\n",
    "|poll()|检查进程是否终止（返回None表示运行中）|if proc.poll() is None: print(\"Running\")|\n",
    "|wait()|阻塞等待进程结束|proc.wait()|\n",
    "|communicate()|交互式输入/输出|stdout, stderr = proc.communicate(input=\"data\")|\n",
    "|terminate()|发送终止信号（SIGTERM）|proc.terminate()|\n",
    "|kill()|强制终止进程（SIGKILL）|proc.kill()|\n",
    "|stdin|进程的标准输入流|proc.stdin.write(\"input\")|\n",
    "|stdout|进程的标准输出流|print(proc.stdout.read())|\n",
    "|stderr|进程的标准错误流|errors = proc.stderr.read()|\n",
    "\n",
    "## 常用参数说明（适用于 run() 和 Popen()）\n",
    "\n",
    "|参数|说明|示例值|\n",
    "|--|--|--|\n",
    "|args|命令（列表或字符串）|[\"ls\", \"-l\"] 或 \"ls -l\"|\n",
    "|stdin|标准输入配置|subprocess.PIPE（管道）、None（继承）|\n",
    "|stdout|标准输出配置|subprocess.PIPE、open('log.txt', 'w')|\n",
    "|stderr|标准错误配置|subprocess.STDOUT（合并到stdout）|\n",
    "|shell|是否通过Shell执行|True（支持字符串命令）|\n",
    "|cwd|工作目录路径|\"/tmp\"|\n",
    "|env|自定义环境变量|{\"PATH\": \"/usr/bin\"}|\n",
    "|timeout|超时时间（秒）|30|\n",
    "|text|输入/输出是否为字符串（非字节）|True|"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "id": "ea06009a-60fb-419b-8e7b-b57ee626c538",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "总计 160\n",
      "-rw-rw-r-- 1 ooj ooj 139385  5月 2日 18:09 数据分析.ipynb\n",
      "-rw-rw-r-- 1 ooj ooj     59  5月 2日 15:50 data.json\n",
      "-rw-rw-r-- 1 ooj ooj     39  5月 2日 18:08 data.pkl\n",
      "-rw-rw-r-- 1 ooj ooj     63  5月 2日 18:05 person.pkl\n",
      "drwxrwxr-x 7 ooj ooj   4096  5月 1日 20:12 venv\n",
      "\n"
     ]
    }
   ],
   "source": [
    "import subprocess\n",
    "\n",
    "# 执行一个简单的 shell 命令\n",
    "result = subprocess.run(['ls', '-l'], capture_output=True, text=True)\n",
    "\n",
    "# 打印命令的输出\n",
    "print(result.stdout)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "62ff2995-7b06-45bb-87dc-b7c85b63e7e9",
   "metadata": {},
   "source": [
    "# queue 模块\n",
    "\n",
    "## queue 模块核心类\n",
    "\n",
    "|类|说明|适用场景|\n",
    "|--|--|--|\n",
    "|queue.Queue|先进先出（FIFO）队列|通用任务队列|\n",
    "|queue.LifoQueue|后进先出（LIFO）队列（类似栈）|需要后进先出的场景|\n",
    "|queue.PriorityQueue|优先级队列（最小堆实现）|按优先级处理任务|\n",
    "|queue.SimpleQueue|更简单的FIFO队列（Python 3.7+）|不需要高级功能的场景|\n",
    "\n",
    "## 通用方法（所有队列类都支持）\n",
    "\n",
    "|方法|说明|示例|返回值|\n",
    "|--|--|--|--|\n",
    "|put(item)|放入元素|q.put(\"task1\")|None|\n",
    "|get()|取出并移除元素|item = q.get()|队列元素|\n",
    "|empty()|判断队列是否为空|if q.empty():|True/False|\n",
    "|full()|判断队列是否已满|if q.full():|True/False|\n",
    "|qsize()|返回队列当前大小|size = q.qsize()|整数|\n",
    "|task_done()|标记任务完成（用于join()）|q.task_done()|None|\n",
    "|join()|阻塞直到所有任务完成|q.join()|None|\n",
    "\n",
    "## 阻塞控制参数\n",
    "\n",
    "|参数|说明|默认值|示例|\n",
    "|--|--|--|--|\n",
    "|block|当队列为空/满时是否阻塞|True|q.get(block=False)|\n",
    "|timeout|阻塞超时时间（秒）|None|q.put(x, timeout=5)|"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "id": "e304c060-d853-4ea0-8428-0d620d1f3224",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "2\n",
      "3\n"
     ]
    }
   ],
   "source": [
    "import queue\n",
    "\n",
    "# 创建一个队列\n",
    "q = queue.Queue()\n",
    "\n",
    "# 向队列中添加元素\n",
    "q.put(1)\n",
    "q.put(2)\n",
    "q.put(3)\n",
    "\n",
    "# 从队列中获取元素\n",
    "print(q.get())  # 输出: 1\n",
    "print(q.get())  # 输出: 2\n",
    "print(q.get())  # 输出: 3"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "57d41bcd-5f40-4107-908b-cf3d57ec0a27",
   "metadata": {},
   "source": [
    "# StringIO 模块\n",
    "\n",
    "|属性/方法|描述|\n",
    "|--|--|\n",
    "|StringIO()|创建一个 StringIO 对象，可以传入初始字符串作为参数。|\n",
    "|write(s)|将字符串 s 写入 StringIO 对象。|\n",
    "|read([size])|从 StringIO 对象中读取最多 size 个字符。如果未指定 size，则读取全部内容。|\n",
    "|readline([size])|从 StringIO 对象中读取一行，最多读取 size 个字符。|\n",
    "|readlines([sizehint])|从 StringIO 对象中读取所有行，并返回一个列表。sizehint 用于限制读取的字符数。|\n",
    "|getvalue()|返回 StringIO 对象中的所有内容，作为一个字符串。|\n",
    "|seek(offset[, whence])|移动文件指针到指定位置。offset 是偏移量，whence 是参考位置（0：文件开头，1：当前位置，2：文件末尾）。|\n",
    "|tell()|返回当前文件指针的位置。|\n",
    "|truncate([size])|截断 StringIO 对象的内容到指定大小。如果未指定 size，则截断到当前文件指针位置。|\n",
    "|close()|关闭 StringIO 对象，释放资源。|\n",
    "|closed|返回一个布尔值，表示 StringIO 对象是否已关闭。|"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "id": "c5d68a44-6105-4de0-b626-f6a93af7ec07",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello, World!\n",
      "This is a test.\n",
      "Hello, World!\n",
      "This is a test.\n"
     ]
    }
   ],
   "source": [
    "from io import StringIO\n",
    "\n",
    "# 创建一个 StringIO 对象\n",
    "string_io = StringIO()\n",
    "\n",
    "# 写入字符串\n",
    "string_io.write(\"Hello, World!\\n\")\n",
    "string_io.write(\"This is a test.\")\n",
    "\n",
    "# 移动文件指针到开头\n",
    "string_io.seek(0)\n",
    "\n",
    "# 读取内容\n",
    "content = string_io.read()\n",
    "print(content)\n",
    "\n",
    "# 获取所有内容\n",
    "value = string_io.getvalue()\n",
    "print(value)\n",
    "\n",
    "# 关闭 StringIO 对象\n",
    "string_io.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e3fead57-36b7-4fce-9ed0-b64711e392c5",
   "metadata": {},
   "source": [
    "# logging 模块\n",
    "\n",
    "## 1. 核心类|\n",
    "\n",
    "|类|说明|示例|\n",
    "|--|--|--|\n",
    "|logging.Logger|记录器，用于发出日志消息（通过 logging.getLogger(name) 获取）|logger = logging.getLogger(\"my_logger\")|\n",
    "|logging.Handler|处理器，决定日志输出位置（如文件、控制台等）|handler = logging.FileHandler(\"app.log\")|\n",
    "|logging.Formatter|格式化器，控制日志输出的格式|formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')|\n",
    "|logging.Filter|过滤器，用于更精细地控制日志记录|filter = logging.Filter(\"module.name\")|\n",
    "\n",
    "## 2. Logger 对象常用方法|\n",
    "\n",
    "|方法|说明|示例|\n",
    "|--|--|--|\n",
    "|logger.setLevel(level)|设置日志级别（如 logging.DEBUG、logging.INFO）|logger.setLevel(logging.DEBUG)|\n",
    "|logger.debug(msg)|记录 DEBUG 级别日志|logger.debug(\"调试信息\")|\n",
    "|logger.info(msg)|记录 INFO 级别日志|logger.info(\"程序启动\")|\n",
    "|logger.warning(msg)|记录 WARNING 级别日志|logger.warning(\"磁盘空间不足\")|\n",
    "|logger.error(msg)|记录 ERROR 级别日志|logger.error(\"操作失败\")|\n",
    "|logger.critical(msg)|记录 CRITICAL 级别日志|logger.critical(\"系统崩溃\")|\n",
    "|logger.addHandler(handler)|添加处理器|logger.addHandler(handler)|\n",
    "|logger.addFilter(filter)|添加过滤器|logger.addFilter(filter)|\n",
    "\n",
    "## 3. Handler 常用类型|\n",
    "\n",
    "|Handler 类型|说明|示例|\n",
    "|--|--|--|\n",
    "|StreamHandler|输出到流（如控制台）|handler = logging.StreamHandler()|\n",
    "|FileHandler|输出到文件|handler = logging.FileHandler(\"app.log\")|\n",
    "|RotatingFileHandler|按文件大小分割日志|handler = logging.RotatingFileHandler(\"app.log\", maxBytes=1e6, backupCount=3)|\n",
    "|TimedRotatingFileHandler|按时间分割日志|handler = logging.TimedRotatingFileHandler(\"app.log\", when=\"midnight\")|\n",
    "|SMTPHandler|通过邮件发送日志|handler = logging.SMTPHandler(\"mail.example.com\", \"from@example.com\", \"to@example.com\", \"Error Log\")|\n",
    "\n",
    "## 4. 日志级别（常量）|\n",
    "\n",
    "|级别|数值|说明|\n",
    "|--|--|--|\n",
    "|CRITICAL|50|严重错误，程序可能无法继续运行|\n",
    "|ERROR|40|错误，但程序仍可运行|\n",
    "|WARNING|30|警告信息（默认级别）|\n",
    "|INFO|20|程序运行信息|\n",
    "|DEBUG|10|调试信息|\n",
    "|NOTSET|0|继承父记录器的级别|\n",
    "\n",
    "## 5. Formatter 常用格式字段|\n",
    "\n",
    "|字段|说明|示例输出|\n",
    "|--|--|--|\n",
    "|%(asctime)s|日志创建时间|2023-01-01 12:00:00,123|\n",
    "|%(levelname)s|日志级别名称|INFO|\n",
    "|%(message)s|日志消息内容|程序启动成功|\n",
    "|%(name)s|记录器名称|my_logger|\n",
    "|%(filename)s|生成日志的文件名|app.py|\n",
    "|%(lineno)d|生成日志的行号|42|\n",
    "|%(funcName)s|生成日志的函数名|main|\n",
    "\n",
    "## 6. 快速配置方法|\n",
    "\n",
    "|方法|说明|示例|\n",
    "|--|--|--|\n",
    "|logging.basicConfig()|一键配置日志级别、处理器和格式（通常在程序入口调用）|logging.basicConfig(level=logging.INFO, format='%(levelname)s - %(message)s')|"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7090c826-eccb-48cc-af79-a6f8ab565be1",
   "metadata": {},
   "source": [
    "# datetime 模块\n",
    "\n",
    "## 1. 核心类\n",
    "\n",
    "|类|说明|示例|\n",
    "|--|--|--|\n",
    "|datetime.date|日期类（年、月、日）|date(2023, 5, 15)|\n",
    "|datetime.time|时间类（时、分、秒、微秒）|time(14, 30, 0)|\n",
    "|datetime.datetime|日期时间类（包含日期和时间）|datetime(2023, 5, 15, 14, 30)|\n",
    "|datetime.timedelta|时间间隔类（用于日期/时间计算）|timedelta(days=5)|\n",
    "|datetime.tzinfo|时区信息基类（需子类化实现）|自定义时区类|\n",
    "\n",
    "## 2. date 对象常用方法/属性\n",
    "\n",
    "|方法/属性|说明|示例|\n",
    "|--|--|--|\n",
    "|date.today()|返回当前本地日期|date.today() → date(2023, 5, 15)|\n",
    "|date.fromisoformat(str)|从 YYYY-MM-DD 字符串解析日期|date.fromisoformat(\"2023-05-15\")|\n",
    "|date.year|年份（只读）|d.year → 2023|\n",
    "|date.month|月份（1-12，只读）|d.month → 5|\n",
    "|date.day|日（1-31，只读）|d.day → 15|\n",
    "|date.weekday()|返回星期几（0=周一，6=周日）|d.weekday() → 0|\n",
    "|date.isoformat()|返回 YYYY-MM-DD 格式字符串|d.isoformat() → \"2023-05-15\"|\n",
    "|date.strftime(format)|自定义格式化输出|d.strftime(\"%Y/%m/%d\") → \"2023/05/15\"|\n",
    "\n",
    "## 3. time 对象常用方法/属性\n",
    "\n",
    "|方法/属性|说明|示例|\n",
    "|--|--|--|\n",
    "|time.hour|小时（0-23，只读）|t.hour → 14|\n",
    "|time.minute|分钟（0-59，只读）|t.minute → 30|\n",
    "|time.second|秒（0-59，只读）|t.second → 0|\n",
    "|time.microsecond|微秒（0-999999，只读）|t.microsecond → 0|\n",
    "|time.isoformat()|返回 HH:MM:SS.mmmmmm 格式字符串|t.isoformat() → \"14:30:00\"|\n",
    "|time.strftime(format)|自定义格式化输出|t.strftime(\"%H:%M\") → \"14:30\"|\n",
    "\n",
    "## 4. datetime 对象常用方法/属性\n",
    "\n",
    "|方法/属性|说明|示例|\n",
    "|--|--|--|\n",
    "|datetime.now()|返回当前本地日期时间|datetime.now() → datetime(2023, 5, 15, 14, 30, 0)|\n",
    "|datetime.utcnow()|返回当前 UTC 日期时间|datetime.utcnow()|\n",
    "|datetime.fromtimestamp(ts)|从时间戳创建 datetime 对象|datetime.fromtimestamp(1684146600)|\n",
    "|datetime.timestamp()|返回时间戳（浮点数秒）|dt.timestamp() → 1684146600.0|\n",
    "|datetime.date()|提取日期部分|dt.date() → date(2023, 5, 15)|\n",
    "|datetime.time()|提取时间部分|dt.time() → time(14, 30)|\n",
    "|datetime.year|年份（同 date）|dt.year → 2023|\n",
    "|datetime.strftime(format)|自定义格式化输出|dt.strftime(\"%Y-%m-%d %H:%M\") → \"2023-05-15 14:30\"|\n",
    "\n",
    "## 5. timedelta 对象常用属性\n",
    "\n",
    "|属性|说明|示例|\n",
    "|--|--|--|\n",
    "|days|天数（可正可负）|delta.days → 5|\n",
    "|seconds|秒数（0-86399）|delta.seconds → 3600（1小时）|\n",
    "|microseconds|微秒数（0-999999）|delta.microseconds → 0|\n",
    "\n",
    "## 6. 常用格式化符号（strftime）\n",
    "\n",
    "|符号|说明|示例输出|\n",
    "|--|--|--|\n",
    "|%Y|四位年份|2023|\n",
    "|%m|两位月份（01-12）|05|\n",
    "|%d|两位日（01-31）|15|\n",
    "|%H|24小时制小时（00-23）|14|\n",
    "|%M|分钟（00-59）|30|\n",
    "|%S|秒（00-59）|00|\n",
    "|%A|完整星期名|Monday|\n",
    "|%a|缩写星期名|Mon|\n",
    "|%B|完整月份名|May|\n",
    "|%b|缩写月份名|May|"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "id": "a6ede350-62a2-45e2-a30a-70f90405c02b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "当前时间: 2025-05-02 18:38:05.474356\n",
      "格式化时间: 2025-05-02 18:38:05\n",
      "10 天后的时间: 2025-05-12 18:38:05.474356\n"
     ]
    }
   ],
   "source": [
    "from datetime import datetime, timedelta\n",
    "\n",
    "# 获取当前日期和时间\n",
    "now = datetime.now()\n",
    "print(\"当前时间:\", now)\n",
    "# 格式化输出\n",
    "formatted_time = now.strftime(\"%Y-%m-%d %H:%M:%S\")\n",
    "print(\"格式化时间:\", formatted_time)\n",
    "# 计算 10 天后的时间\n",
    "future_time = now + timedelta(days=10)\n",
    "print(\"10 天后的时间:\", future_time)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f5cf2b9c-fb8a-4f12-b9ba-dc3642645d54",
   "metadata": {},
   "source": [
    "# re 模块\n",
    "\n",
    "## 1. 核心函数\n",
    "\n",
    "|方法|说明|示例|\n",
    "|--|--|--|\n",
    "|re.compile(pattern)|预编译正则表达式（提升复用性能）|pat = re.compile(r'\\d+')|\n",
    "|re.search(pattern, string)|搜索字符串中第一个匹配项|re.search(r'\\d+', 'a1b2') → 匹配 '1'|\n",
    "|re.match(pattern, string)|从字符串起始位置匹配|re.match(r'\\d+', '123a') → 匹配 '123'|\n",
    "|re.fullmatch(pattern, string)|整个字符串完全匹配|re.fullmatch(r'\\d+', '123') → 匹配 '123'|\n",
    "|re.findall(pattern, string)|返回所有非重叠匹配的列表|re.findall(r'\\d+', 'a1b22c') → ['1', '22']|\n",
    "|re.finditer(pattern, string)|返回所有匹配的迭代器（含位置信息）|for m in re.finditer(r'\\d+', 'a1b2'): print(m.group())|\n",
    "|re.sub(pattern, repl, string)|替换匹配项|re.sub(r'\\d+', 'X', 'a1b2') → 'aXbX'|\n",
    "|re.split(pattern, string)|按匹配项分割字符串|re.split(r'\\d+', 'a1b2c') → ['a', 'b', 'c']|\n",
    "\n",
    "## 2. 匹配对象（Match）方法/属性\n",
    "\n",
    "|方法/属性|说明|示例|\n",
    "|--|--|--|\n",
    "|group()|返回整个匹配的字符串|m.group() → 'abc'|\n",
    "|group(n)|返回第n个捕获组的内容|m = re.search(r'(\\d)(\\d)', '12'); m.group(1) → '1'|\n",
    "|groups()|返回所有捕获组的元组|m.groups() → ('1', '2')|\n",
    "|start()/end()|匹配的起始/结束位置|m.start() → 0|\n",
    "|span()|返回匹配范围 (start, end)|m.span() → (0, 2)|\n",
    "\n",
    "## 3. 正则表达式元字符（部分）\n",
    "\n",
    "|元字符|说明|示例匹配|\n",
    "|--|--|--|\n",
    "|.|匹配任意字符（除换行符）|a.c → 'abc'|\n",
    "|\\d|匹配数字|\\d+ → '123'|\n",
    "|\\D|匹配非数字|\\D+ → 'abc'|\n",
    "|\\w|匹配单词字符（字母、数字、下划线）|\\w+ → 'Ab_1'|\n",
    "|\\W|匹配非单词字符|\\W+ → '!@#'|\n",
    "|\\s|匹配空白字符（空格、制表符等）|\\s+ → ' \\t'|\n",
    "|\\S|匹配非空白字符|\\S+ → 'abc'|\n",
    "|[]|字符集合|[A-Za-z] → 任意字母|\n",
    "|^|匹配字符串开头|^\\d+ → 开头的数字|\n",
    "|$|匹配字符串结尾|\\d+$ → 结尾的数字|\n",
    "|*|匹配前一个字符0次或多次|a* → '', 'aaa'|\n",
    "|+|匹配前一个字符1次或多次|a+ → 'a', 'aaa'|\n",
    "|?|匹配前一个字符0次或1次|a? → '', 'a'|\n",
    "|{m,n}|匹配前一个字符m到n次|a{2,3} → 'aa', 'aaa'|\n",
    "|||或操作|cat|dog → 'cat' 或 'dog'|\n",
    "|()|捕获分组|(\\d+) → 提取数字|\n",
    "\n",
    "## 4. 编译标志（flags 参数）\n",
    "\n",
    "|标志|说明|示例|\n",
    "|--|--|--|\n",
    "|re.IGNORECASE (re.I)|忽略大小写|re.search(r'abc', 'ABC', re.I)|\n",
    "|re.MULTILINE (re.M)|多行模式（影响 ^ 和 $）|re.findall(r'^\\d+', '1\\n2', re.M) → ['1', '2']|\n",
    "|re.DOTALL (re.S)|让 . 匹配包括换行符的所有字符|re.search(r'a.*b', 'a\\nb', re.S)|\n",
    "|re.ASCII|让 \\w, \\W 等仅匹配ASCII字符|re.search(r'\\w+', 'こん', re.ASCII) → 无匹配|\n",
    "|re.VERBOSE (re.X)|允许正则中添加注释和空格|re.compile(r'''\\d+ # 匹配数字''', re.X)|"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "id": "adf91163-69f1-40dd-b5a2-03eba57b3d9c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "有效的电子邮件地址\n"
     ]
    }
   ],
   "source": [
    "import re\n",
    "\n",
    "pattern = r\"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$\"\n",
    "email = \"example@example.com\"\n",
    "\n",
    "if re.match(pattern, email):\n",
    "    print(\"有效的电子邮件地址\")\n",
    "else:\n",
    "    print(\"无效的电子邮件地址\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "id": "b20ef0a2-78ab-4b4b-9af6-e5015a920850",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "找到的电话号码: 123-456-7890\n"
     ]
    }
   ],
   "source": [
    "pattern = r\"\\d{3}-\\d{3}-\\d{4}\"\n",
    "text = \"My phone number is 123-456-7890.\"\n",
    "\n",
    "match = re.search(pattern, text)\n",
    "if match:\n",
    "    print(\"找到的电话号码:\", match.group())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fece10d1-97e7-48bc-90ba-74892c271697",
   "metadata": {},
   "source": [
    "# csv 模块\n",
    "\n",
    "## csv 模块核心方法\n",
    "\n",
    "|方法|说明|示例|\n",
    "|--|--|--|\n",
    "|csv.reader()|从文件对象读取 CSV 数据|reader = csv.reader(file)|\n",
    "|csv.writer()|将数据写入 CSV 文件|writer = csv.writer(file)|\n",
    "|csv.DictReader()|将 CSV 行读取为字典（带表头）|dict_reader = csv.DictReader(file)|\n",
    "|csv.DictWriter()|将字典写入 CSV 文件（需指定字段名）|dict_writer = csv.DictWriter(file, fieldnames)|\n",
    "|csv.register_dialect()|注册自定义 CSV 格式（如分隔符）|csv.register_dialect('mydialect', delimiter='|')|\n",
    "|csv.unregister_dialect()|删除已注册的方言|csv.unregister_dialect('mydialect')|\n",
    "|csv.list_dialects()|列出所有已注册的方言|print(csv.list_dialects())|\n",
    "\n",
    "## csv.reader 和 csv.writer 对象常用方法\n",
    "\n",
    "|方法|说明|适用对象|\n",
    "|--|--|--|\n",
    "|__next__()|迭代读取下一行（或使用 for 循环）|reader|\n",
    "|writerow(row)|写入单行数据|writer|\n",
    "|writerows(rows)|写入多行数据（列表的列表）|writer|\n",
    "\n",
    "## csv.DictReader 和 csv.DictWriter 对象特性\n",
    "\n",
    "|特性/方法|说明|示例|\n",
    "|--|--|--|\n",
    "|fieldnames|字段名列表（DictReader 自动从首行获取）|dict_reader.fieldnames|\n",
    "|writeheader()|写入表头行（DictWriter 专用）|dict_writer.writeheader()|\n",
    "\n",
    "## 常用参数说明\n",
    "\n",
    "|参数|说明|示例值|适用方法|\n",
    "|--|--|--|--|\n",
    "|delimiter|字段分隔符|','（默认）, '\\t'|reader/writer|\n",
    "|quotechar|引用字符（包围特殊字段）|'\"'（默认）|reader/writer|\n",
    "|quoting|引用规则|csv.QUOTE_ALL（全部引用）|reader/writer|\n",
    "|skipinitialspace|忽略分隔符后的空格|True/False|reader|\n",
    "|lineterminator|行结束符|'\\r\\n'（默认）|writer|\n",
    "|dialect|预定义的方言名称|'excel'（默认）|所有方法|"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "id": "59475b46-1849-4128-b097-e1e06a175607",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'Name': 'Alice', 'Age': '30', 'City': 'New York'}\n",
      "{'Name': 'Bob', 'Age': '25', 'City': 'Los Angeles'}\n"
     ]
    }
   ],
   "source": [
    "import csv\n",
    "\n",
    "data = [\n",
    "    {'Name': 'Alice', 'Age': '30', 'City': 'New York'},\n",
    "    {'Name': 'Bob', 'Age': '25', 'City': 'Los Angeles'}\n",
    "]\n",
    "\n",
    "with open('data.csv', mode='w', encoding='utf-8', newline='') as file:\n",
    "    fieldnames = ['Name', 'Age', 'City']\n",
    "    csv_dict_writer = csv.DictWriter(file, fieldnames=fieldnames)\n",
    "    # 写入表头\n",
    "    csv_dict_writer.writeheader()\n",
    "    # 写入数据\n",
    "    for row in data:\n",
    "        csv_dict_writer.writerow(row)\n",
    "\n",
    "with open('data.csv', mode='r', encoding='utf-8') as file:\n",
    "    csv_dict_reader = csv.DictReader(file)\n",
    "    for row in csv_dict_reader:\n",
    "        print(row)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "af5ca55e-37c4-4d20-86b0-efe454621814",
   "metadata": {},
   "source": [
    "# threading 模块\n",
    "\n",
    "## 1. 核心类\n",
    "\n",
    "|类/方法/属性|说明|示例|\n",
    "|--|--|--|\n",
    "|threading.Thread|线程类，用于创建和管理线程|t = Thread(target=func, args=(1,))|\n",
    "|threading.Lock|互斥锁（原始锁）|lock = Lock()|\n",
    "|threading.RLock|可重入锁（同一线程可多次获取）|rlock = RLock()|\n",
    "|threading.Event|事件对象，用于线程同步|event = Event()|\n",
    "|threading.Condition|条件变量，用于复杂线程协调|cond = Condition()|\n",
    "|threading.Semaphore|信号量，控制并发线程数|sem = Semaphore(3)|\n",
    "|threading.BoundedSemaphore|有界信号量（防止计数超过初始值）|b_sem = BoundedSemaphore(2)|\n",
    "|threading.Timer|定时器线程，延迟执行|timer = Timer(5.0, func)|\n",
    "|threading.local|线程局部数据（各线程独立存储）|local_data = threading.local()|\n",
    "\n",
    "## 2. Thread 对象常用方法/属性\n",
    "\n",
    "|方法/属性|说明|示例|\n",
    "|--|--|--|\n",
    "|start()|启动线程|t.start()|\n",
    "|run()|线程执行的方法（可重写）|自定义类时覆盖此方法|\n",
    "|join(timeout=None)|阻塞当前线程，直到目标线程结束|t.join()|\n",
    "|is_alive()|检查线程是否在运行|if t.is_alive():|\n",
    "|name|线程名称（可修改）|t.name = \"Worker-1\"|\n",
    "|daemon|守护线程标志（主线程退出时自动结束）|t.daemon = True|\n",
    "|ident|线程标识符（未启动时为 None）|print(t.ident)|\n",
    "\n",
    "## 3. Lock/RLock 常用方法\n",
    "\n",
    "|方法|说明|示例|\n",
    "|--|--|--|\n",
    "|acquire(blocking=True, timeout=-1)|获取锁（阻塞或非阻塞）|lock.acquire()|\n",
    "|release()|释放锁|lock.release()|\n",
    "|locked()|检查锁是否被占用|if not lock.locked():|\n",
    "\n",
    "## 4. Event 常用方法\n",
    "\n",
    "|方法|说明|示例|\n",
    "|--|--|--|\n",
    "|set()|设置事件为真，唤醒所有等待线程|event.set()|\n",
    "|clear()|重置事件为假|event.clear()|\n",
    "|wait(timeout=None)|阻塞直到事件为真或超时|event.wait(2.0)|\n",
    "|is_set()|检查事件状态|if event.is_set():|\n",
    "\n",
    "## 5. Condition 常用方法\n",
    "\n",
    "|方法|说明|示例|\n",
    "|--|--|--|\n",
    "|wait(timeout=None)|释放锁并阻塞，直到被通知或超时|cond.wait()|\n",
    "|notify(n=1)|唤醒最多 n 个等待线程|cond.notify(2)|\n",
    "|notify_all()|唤醒所有等待线程|cond.notify_all()|\n",
    "\n",
    "## 6. 模块级函数/属性\n",
    "\n",
    "|函数/属性|说明|示例|\n",
    "|--|--|--|\n",
    "|threading.active_count()|返回当前活跃线程数|print(threading.active_count())|\n",
    "|threading.current_thread()|返回当前线程对象|print(threading.current_thread().name)|\n",
    "|threading.enumerate()|返回所有活跃线程的列表|for t in threading.enumerate():|\n",
    "|threading.main_thread()|返回主线程对象|if threading.current_thread() is threading.main_thread():|\n",
    "|threading.get_ident()|返回当前线程的标识符（Python 3.3+）|print(threading.get_ident())|"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 68,
   "id": "7b7f5665-e5a1-4fc8-becc-18a04c3e8d92",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "处理项目: 0\n",
      "处理项目: 1\n",
      "处理项目: 2\n",
      "处理项目: 3\n",
      "处理项目: 4\n",
      "处理项目: 5\n",
      "处理项目: 6\n",
      "处理项目: 7\n",
      "处理项目: 8\n",
      "处理项目: 9\n",
      "所有项目处理完毕\n"
     ]
    }
   ],
   "source": [
    "import threading\n",
    "import queue\n",
    "\n",
    "def worker(q):\n",
    "    while not q.empty():\n",
    "        item = q.get()\n",
    "        print(f\"处理项目: {item}\")\n",
    "        q.task_done()\n",
    "\n",
    "# 创建一个队列并填充数据\n",
    "q = queue.Queue()\n",
    "for i in range(10):\n",
    "    q.put(i)\n",
    "\n",
    "# 创建线程实例\n",
    "thread1 = threading.Thread(target=worker, args=(q,))\n",
    "thread2 = threading.Thread(target=worker, args=(q,))\n",
    "# 启动线程\n",
    "thread1.start()\n",
    "thread2.start()\n",
    "# 等待队列中的所有项目被处理完毕\n",
    "q.join()\n",
    "print(\"所有项目处理完毕\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e77e8345-8d12-455b-b883-382c6c1c99ca",
   "metadata": {},
   "source": [
    "# asyncio 模块\n",
    "\n",
    "## 1. 核心函数\n",
    "\n",
    "|方法/函数|说明|示例|\n",
    "|--|--|--|\n",
    "|asyncio.run(coro)|运行异步主函数（Python 3.7+）|asyncio.run(main())|\n",
    "|asyncio.create_task(coro)|创建任务并加入事件循环|task = asyncio.create_task(fetch_data())|\n",
    "|asyncio.gather(*coros)|并发运行多个协程|await asyncio.gather(task1, task2)|\n",
    "|asyncio.sleep(delay)|异步等待（非阻塞）|await asyncio.sleep(1)|\n",
    "|asyncio.wait(coros)|控制任务完成方式|done, pending = await asyncio.wait([task1, task2])|\n",
    "\n",
    "## 2. 事件循环（Event Loop）\n",
    "\n",
    "|方法|说明|示例|\n",
    "|--|--|--|\n",
    "|loop.run_until_complete(future)|运行直到任务完成|loop.run_until_complete(main())|\n",
    "|loop.run_forever()|永久运行事件循环|loop.run_forever()|\n",
    "|loop.stop()|停止事件循环|loop.stop()|\n",
    "|loop.close()|关闭事件循环|loop.close()|\n",
    "|loop.call_soon(callback)|安排回调函数立即执行|loop.call_soon(print, \"Hello\")|\n",
    "|loop.call_later(delay, callback)|延迟执行回调|loop.call_later(5, callback)|\n",
    "\n",
    "## 3. 协程（Coroutine）与任务（Task）\n",
    "\n",
    "|方法/装饰器|说明|示例|\n",
    "|--|--|--|\n",
    "|@asyncio.coroutine|协程装饰器（旧版，Python 3.4-3.7）|@asyncio.coroutine|\n",
    "|def old_coro():|\n",
    "|async def|定义协程（Python 3.5+）|async def fetch():|\n",
    "|task.cancel()|取消任务|task.cancel()|\n",
    "|task.done()|检查任务是否完成|if task.done():|\n",
    "|task.result()|获取任务结果（需任务完成）|data = task.result()|\n",
    "\n",
    "## 4. 同步原语（类似threading）\n",
    "\n",
    "|类|说明|示例|\n",
    "|--|--|--|\n",
    "|asyncio.Lock()|异步互斥锁|lock = asyncio.Lock()|\n",
    "|async with lock:|\n",
    "|asyncio.Event()|事件通知|event = asyncio.Event()|\n",
    "|await event.wait()|\n",
    "|asyncio.Queue()|异步队列|queue = asyncio.Queue()|\n",
    "|await queue.put(item)|\n",
    "|asyncio.Semaphore()|信号量|sem = asyncio.Semaphore(5)|\n",
    "|async with sem:|\n",
    "\n",
    "## 5. 网络与子进程\n",
    "\n",
    "|方法/类|说明|示例|\n",
    "|--|--|--|\n",
    "|asyncio.open_connection()|建立TCP连接|reader, writer = await asyncio.open_connection('host', 80)|\n",
    "|asyncio.start_server()|创建TCP服务器|server = await asyncio.start_server(handle, '0.0.0.0', 8888)|\n",
    "|asyncio.create_subprocess_exec()|创建子进程|proc = await asyncio.create_subprocess_exec('ls')|\n",
    "\n",
    "## 6. 实用工具\n",
    "\n",
    "|方法|说明|示例|\n",
    "|--|--|--|\n",
    "|asyncio.current_task()|获取当前任务|task = asyncio.current_task()|\n",
    "|asyncio.all_tasks()|获取所有任务|tasks = asyncio.all_tasks()|\n",
    "|asyncio.shield(coro)|保护任务不被取消|await asyncio.shield(critical_task)|\n",
    "|asyncio.wait_for(coro, timeout)|带超时的等待|try: await asyncio.wait_for(task, 5)|"
   ]
  },
  {
   "cell_type": "raw",
   "id": "9b00e68e-4d7f-4d28-a6b5-2589e8696f90",
   "metadata": {},
   "source": [
    "import asyncio\n",
    "\n",
    "async def long_task():\n",
    "    await asyncio.sleep(10)\n",
    "    print(\"Task finished\")\n",
    "\n",
    "async def main():\n",
    "    try:\n",
    "        await asyncio.wait_for(long_task(), timeout=5)\n",
    "    except asyncio.TimeoutError:\n",
    "        print(\"Task timed out\")\n",
    "\n",
    "asyncio.run(main())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fe04b050-f15d-4e0b-91b8-68cf4650362b",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
